本文介绍了Nhibernate中多对多集合的更新导致联接表中的多个删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,其中包含一个使用Fluent Nhibernate映射到多对多数据库关系的集合.映射如下-

I have a class that contains a collection that is mapped to a many-to-many database relationship using Fluent Nhibernate. The mapping is as below -

Table("Book");
Id(x => x.Id);
Map(x => x.Title);
Map(x => x.NumberOfPages);
HasManyToMany(x => x.Authors)
.Cascade.AllDeleteOrphan()
.Table("BookAuthor")
.ParentKeyColumn("BookId")
.ChildKeyColumn("AuthorId");

然后我获得该类的一个实例,并使用下面的代码将一个项目添加到authors集合中-

I then get an instance of this class and add an item to the authors collection using the code below -

var book = session.CreateCriteria(typeof(Book)).UniqueResult<Book>();
Author author = new Author {Name="Phil Moran",Age=51};
book.Authors.Add(author);
session.SaveOrUpdate(book); 

数据库已成功更新,但是Nhibernate通过首先删除链接到已更新书籍的表中的所有记录,然后重新填充所有数据以及新作者所需的额外记录来更新BookAuthor表. Nhibernate为什么要这样做?我希望它只是将包含书籍和作者详细信息的单个记录添加到多对多表(BookAuthor)中,而不执行任何删除操作.我可以通过映射更改此行为吗?

The database is updated succesfully but Nhibernate updates the BookAuthor table by firstly deleting all the records within it linked to the updated book, then repopulating all the data plus the extra record required for the new author. Why is Nhibernate doing this? I would expect it to simply add a single record containing the book and author details to the many-to-many table (BookAuthor) and not perform any of the delete actions. Can I change this behaviour via my mappings?

推荐答案

在将集合映射为bag时会发生这种情况(我想这是FluentNH中的默认值).

That happens when the collection is mapped as a bag (I guess that's the default in FluentNH).

改为使用setlistidbag.

这篇关于Nhibernate中多对多集合的更新导致联接表中的多个删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 20:05