Avoid uninstalling and reinstalling when updating compnonent mapped to Fluent NHibernate

Consider the following scenario: the user has a set of spices, and each spice can be “in stock” or “run out” (indicated by the RunOut logical property).

I matched this relationship with FluentNHibernate using such a component

public UserMappings() { Id(x => x.Id); Map(x => x.FirstName); Map(x => x.LastName); Map(x => x.Email).Length(255).Unique(); HasOne(x => x.Credentials).Cascade.SaveUpdate().Fetch.Select(); HasMany(x => x.Spices) .Component(c => { c.Map(x => x.RunOut); c.References(x => x.BaseSpice).Fetch.Join(); }).Table("User_Spices").Fetch.Join(); } 

The Spice collection in the above display belongs to the UserSpice class (value object):

 public class UserSpice { public virtual Spice BaseSpice { get; protected set; } public virtual bool RunOut { get; protected set; } public static UserSpice Create(Spice baseSpice, bool runOut) { var userSpice = new UserSpice {BaseSpice = baseSpice, RunOut = runOut}; return userSpice; } } 

This works "fine" - however, when I update any of the components (for example, changing spice to RunOut = true), all custom spices are removed and reinserted.

I understand that this is because NHibernate does not have the ability to uniquely identify which sps-spice link it should update.

How can I simulate this differently to avoid this delete-and-reinsert behavior?

+4
source share
2 answers

NHibernate has different types of collections. Some of them benefit from a more complex display, such as <list> or <idbag> . Please read this part from the documentation about collection type issues:

http://nhibernate.info/doc/nh/en/index.html#performance-collections-mostefficientupdate

short shutter speed

There is perhaps another advantage that collections have indexed over sets for many, many associations or collections of values. Due to the ISet structure, NHibernate never updates a row when an item is "modified." Changes in ISet always work through INSERT and DELETE (single lines). Once again, this consideration does not apply to one of many associations.

So, if you use an indexed list (or even an idbag), NHibernate can figure out which item in the collection has changed and can even cause UDPATE

And there is another question where you can find out how to map an indexed list

Fluent Nhibernate - Listing results in a NullReferenceException?

short summary:

HasMany (x => x.MyChildren) .AsList (x => x.Column ("Ordinal")) KeyColumn ("AID") Not.KeyNullable (); ..

+3
source

implement Equals / GetHashcode in UserSpice with a business rule of uniqueness, for example. BaseSpice and add .AsSet() to HasMany(x => x.Spices) . Datatype of Spices should be ICollection<> or Iesi.Collections.Generic.ISet<> or with a little extra effort System.Collection.Generic.ISet<> .

+1
source

Source: https://habr.com/ru/post/1445952/


All Articles