user3608068 user3608068 - 9 months ago 40
C# Question

NHibernate clearing associations - wrong query generated

Suppose I have following models:

public class User
public virtual int Id { get; set; }
public virtual ICollection<Role> Roles { get; set; }

public class Role
public virtual int Id { get; set; }
public virtual ICollection<User> Users { get; set; }

I have them joined by many-to-many relationship so when I do something like:


NHibernate will generate query:

DELETE FROM User_Role WHERE UserId = @p1 AND RoleId = @p2

which is fine, except for when
is last item in
collection. Then the query will look like this:

DELETE FROM User_Role WHERE UserId = @p1

so no checking for RoleId this time, just deleting whone collection. Which is wrong! I have many threads working on same data and this second query causes me to lose associations. Suppose we have user with single role loaded by 2 threads at the same time. One adds new role and saves this first, now the second thread removes role. Then trying to
will cause it to delete not single association but also second one just created by other thread.

So the question is: how to force NH to always use this first query?

Answer Source

After investigating code of NHibernate I came to conclusion that there is no way to change this.