NHibernate多对多插入前将删除所有关联 [英] NHibernate Many-To-Many Is Deleting All Associations Before Inserting

查看:68
本文介绍了NHibernate多对多插入前将删除所有关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Users表和一个Networks表,它们之间有多对多的关系(一个用户可能对多个网络很长,一个网络可能包含许多用户).多对多关系保存在"UserNetworks"表中,该表仅包含两列,即UserId和NetworkId.

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:

User.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆