user3608068 user3608068 - 19 days ago 6
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:

user.Roles.Remove(role);
Session.Save(user);


NHibernate will generate query:

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


which is fine, except for when
role
is last item in
Roles
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
Save
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

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

Comments