Note that there are some explanatory texts on larger screens.

plurals
  1. POCan nhibernate check for unique constraints, without it being the primary key
    text
    copied!<p>I have a simple class, that has a <code>Name</code> member, used to uniquely identify an instance. This class is referenced in a ManyToMany-mapping which will use the <code>Name</code>(since it is the primary key) to create the mapping-table. The type of strings involved makes this very slow (length > 128 chars, often only differing in the last few). To speed it up I'd like to create an <code>auto_increment</code> column (I'm using MySQL) for the join, while still being able to have nhibernate sort out the uniqueness of my objects using the <code>Name</code>-column.</p> <p>Here is an example of what it looks like. In reality the objects are a lot larger.</p> <pre><code>class MyObject{ public String Name; public String Value; } //Mapping Id(x =&gt; x.Name) .Length(255) .Unique(); Map(x =&gt; x.Value); </code></pre> <p>This works as intended. If I add a new <code>MyObject</code> to the table nhibernate will do a select first to see if a record with the same <code>Name</code> is already in the table.</p> <p>I have an <code>ObjectHolder</code> that has a Set of <code>MyObject</code></p> <pre><code>class ObjectHolder{ public UInt64 Id; public ICollection&lt;MyObject&gt; MyObjects; } //Mapping Id(x =&gt; x.Id) .GeneratedBy.Native(); HasManyToMany(x =&gt; x.MyObjects) .AsSet() .Cascade.SaveUpdate(); </code></pre> <p>This will create a mapping using <code>ObjectHolder.Id</code> and <code>MyObject.Name</code>, which is slow. I want the <code>MyObject</code> to have an Id-column that is autogenerated and only used for the mapping-table, but not for the select-to-see-if-it-exists-checking that nhibernate does with the primary key.</p> <p>I have altered the mapping to</p> <pre><code>class MyObject{ public UInt64 Id; public String Name; public String Value; } //Mapping Id(x =&gt; x.Id) .GeneratedBy.Native(); Map(x =&gt; x.Name) .Length(255) .Unique(); Map(x =&gt; x.Value); </code></pre> <p>This will create an auto_increment column and use it for the mapping-table, however it will now no longer check correctly if a record with the same <code>Name</code> already exists, which leads to duplicate entry exceptions.</p> <p>Can I tell nhibernate to check the <code>Name</code> column instead the id, or annotate the <code>Id</code>-column so it is only used as a foreign key, but nothing else? Do I have to modify the manyToMany mapping?</p> <p>Edit: It seems even worse if I have to use composite ids. All id properties are saved twice, once in the object itself and once in the mapping, which adds a huge time and storage space overhead.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload