NHibernate recreates each related item

I have very simple object models.

public class Contact { public virtual int Id { get; set; } public virtual string Name { get; set; } public virtual Device Device { get; set; } public virtual IList<string> Numbers { get; set; } public Contact() { Numbers = new System.Collections.Generic.List<string>(3); } } 

As you can see, the Contact class has a relationship with Numbers, which is a list of strings.

Here's the mapping:

  Id(x => x.Id).GeneratedBy.Assigned(); Map(x => x.Name); References(x => x.Device, "DeviceId"); Table("Contacts"); HasMany(x => x.Numbers) .Table("ContactNumbers") .Element("Number") .KeyColumn("ContactId") .LazyLoad() .Cascade.All() .Not .Inverse(); 

Please note: I cannot and do not want the collection to be inverse = true, because it is just a collection of strings. This means that Contact is responsible for updating Numbers records. Now my problem is that whenever I try to add a new number to an existing contact, it deletes all the associated numbers and recreates them individually. Is NHibernate enough to detect changes and update only changed items?

I think there should be a simple solution for my problem, but I don’t know what.

Any help would be appreciated.

+4
source share
1 answer

Actually documented in NHibernate documentation.

Bags are the worst case. Since the bag allows duplicate values ​​and does not have an index column, the primary key cannot be determined. NHibernate has no way of distinguishing duplicate lines. NHibernate solves this problem by completely deleting (in one DELETE) and re-creating the collection whenever it changes. This can be very inefficient.

Try using the <idbag> and create a surrogate primary key for this table. Unfortunately, it seems that <idbag> is not yet supported on FluentNHibernate .

Also, see other collection mapping options .

+7
source

All Articles