NHibernate loads proxy objects in behavior that I cannot control

My schema

I have a class diagram similar to the above picture. I use NHibernate to execute CRUD commands on objects. When I write to the permissions table (adds the role to the collection of user roles and vice versa), NHibernate starts acting weird. I have a method called UpdateRoles () that ensures that all roles are updated. This method fails because NHibernate sometimes generates proxy objects, so UpdateRoles () now think that the Role does not exist and creates a new object (which leads to duplication of my hierarchy). I found a template when NHibernate loads objects as a proxy:

enter image description here

Case 1 does not work, Case 2 does. It happens that in case 1, the user is added to the user collection of each role at all three levels of the hierarchy. It works as intended.

In case 2, the user is added only to the last level in the hierarchy. Now the parent role (uCommerce) is loaded as a proxy object. My RoleMap looks like this:

References(x => x.ParentRole).Nullable().Column("ParentRoleId"); HasManyToMany(x => x.Users).AsSet().Table("uCommerce_Permission"); HasMany(x => x.Roles).Inverse().KeyColumn("ParentRoleId").Cascade.AllDeleteOrphan(); 

My UserMap looks like this:

 HasManyToMany(x => x.Roles).AsSet().Table("uCommerce_Permission"); 

How can I prevent NHibernate from doing this? I am using Fluennt NHibernate. Indication of Not (). LazyLoad () does not prevent the problem. Also, I read that specifying this is a bad programming case.

+4
source share
1 answer

1)

 var proxy = parent as INHibernateProxy; if (proxy != null) { // var t = x.GetType(); becomes var t = proxy.HibernateLazyInitializer.GetImplementation().GetType(); } 

or 2)

 References(x => x.ParentRole).Nullable().Column("ParentRoleId").Not.LazyLoad(); 

or 3)

 ReferencesAny(x => x.ParentRole) .Nullable() .EntityIdentifierColumn("ParentRoleId") .EntityTypeColumn("parentdiscriminator"); typeof(CreateProductRole).IsAssignableFrom(role.Parent.GetType()). 

1) and 2) are basically the same, the parent is not lazyloaded

3) means that each role knows the type of its parent, so when creating a proxy server, it is a proxy server for the actual role type ( CreateProductRoleProxy ), not RoleProxy

0
source

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


All Articles