NHibernate多对多在插入前删除所有关联 [英] NHibernate Many-To-Many Is Deleting All Associations Before Inserting
问题描述
我有一个 Users 表和一个 Networks 表,它们之间存在多对多关系(一个用户可能长到多个网络,一个网络可能包含多个用户).多对多关系保存在只有两列 UserId 和 NetworkId 的UserNetworks"表中.
I have a Users table and a Networks table with a many-to-many relationship between them (a user may be long to multiple networks and a network may contain many users). The many-to-many relationship is held in a "UserNetworks" table that simply has two columns, UserId and NetworkId.
我的课程是这样的:
public class User
{
public IList<Network> Networks {get; set;}
}
public class Network
{
public IList<Usre> Users {get; set;}
}
这些多对多集合的 NHibernate 映射如下所示:
The NHibernate mappings for these many-to-many collections looks like this:
用户.hbm.xml:
User.hbm.xml:
<bag name="Networks" table="UserNetworks" cascade="save-update" inverse="true">
<key column="UserId" />
<many-to-many class="Network" column="NetworkId" />
</bag>
Network.hbm.xml:
Network.hbm.xml:
<bag name="Users" table="UserNetworks" cascade="save-update">
<key column="NetworkId" />
<many-to-many class="User" column="UserId" />
</bag>
在我的代码中,我在用户和网络之间创建了一个关联,如下所示:
In my code, I create an association between a user and a network like so:
user.Networks.Add(network);
network.Users.Add(user);
我希望 SQL 运行只对 UserNetworks 表执行一次 INSERT.相反,它对 NetworkID = X 的 UserNetworks 表执行 DELETE,然后继续将所有 UserNetworks 行连同新关联一起重新插入.
I would expect the SQL run to simply perform one INSERT to the UserNetworks table. Instead, it executes a DELETE on the UserNetworks table with NetworkID = X, then proceeds to reinsert all the UserNetworks rows back in along with the new association.
我做错了什么?
推荐答案
行为是设计使然.看,NH 不知道列表中的当前/新/已删除内容.因此,删除所有内容并在列表中插入任何内容都是有意义的.
The behaviour is by design. See, NH do not know what's current/new/deleted in the list. So by deleting all and inserting whatever in the list will make sense.
这篇关于NHibernate多对多在插入前删除所有关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!