开发者

nhibernate many to many deletes

开发者 https://www.devze.com 2022-12-28 09:32 出处:网络
I have 2 classes that have a many to many relationship. What i\'d like to happen is that whenever i delete one side ONLY the association records will be deleted with no concern which side i delete.

I have 2 classes that have a many to many relationship. What i'd like to happen is that whenever i delete one side ONLY the association records will be deleted with no concern which side i delete.

simplified model:

classes:

class Qualification
{
     IList<ProfessionalListing> ProfessionalListings 
}

class ProfessionalListing
{
     IList<Qualification> Qualifications

     void AddQualification(Qualification qualification)
     {
        Qualifications.Add(qualification);
        qualification.ProfessionalListings.Add(this);
     } 
}

fluent automapping with overrides:

void Override(AutoMapping<Qualification> mapping)
{
     mapping.HasManyToMany(x => x.ProfessionalListings).Inverse();
}

void Override(AutoMapping<Professiona开发者_C百科lListing> mapping)
{
    mapping.HasManyToMany(x => x.Qualifications).Not.LazyLoad();
}

I'm trying various combinations of cascade and inverse settings but can never get there. If i have no cascades and no inverse i get duplicated entities in my collections. Setting inverse on one side makes the duplication go away but when i try to delete a qualification i get a 'deleted object would be re-saved by cascade'.

How do i do this?

Should i be responsible for clearing the associations of each object i delete?


The many-to-many table is actually the persistent form of the lists (ProfessionalListings and Qualifications). When you delete one of the objects, it is still in the list of the other, isn't it?

You can't expect from NHibernate that it updates your list. For instance, if you delete a Qualification in the database, it is still in the list Qualifications, because you didn't remove it there. NHibernate doesn't (and shouldn't be allowed to) update your list.

ProfessionalListings is the inverse list, this means it is only loaded, but not stored. You need at least to update the Qualifications list when a Qualification is deleted. This is regular consistency within your class model which is managed by the business logic.


If you need to delete a connected object, you can configure AllDeleteOrphan cascade setting. Then if you remove object from association it will be removed

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号