问题描述
我使用流利的NHibernate和有一些问题得到一个多对多的关系设置与我的课之一。这可能是一个愚蠢的错误,但我一直在坚持一点点努力得到它的工作。不管怎么说,我有多对多的关系,一对夫妇类。
I am using Fluent NHibernate and having some issues getting a many to many relationship setup with one of my classes. It's probably a stupid mistake but I've been stuck for a little bit trying to get it working. Anyways, I have a couple classes that have Many-Many relationships.
public class Person
{
public Person()
{
GroupsOwned = new List<Groups>();
}
public virtual IList<Groups> GroupsOwned { get; set; }
}
public class Groups
{
public Groups()
{
Admins= new List<Person>();
}
public virtual IList<Person> Admins{ get; set; }
}
通过映射看起来像这样
联系人:...
HasManyToMany<Groups>(x => x.GroupsOwned)
.WithTableName("GroupAdministrators")
.WithParentKeyColumn("PersonID")
.WithChildKeyColumn("GroupID")
.Cascade.SaveUpdate();
组:...
Groups: ...
HasManyToMany<Person>(x => x.Admins)
.WithTableName("GroupAdministrators")
.WithParentKeyColumn("GroupID")
.WithChildKeyColumn("PersonID")
.Cascade.SaveUpdate();
当我运行我的集成测试,基本上我创建一个新的个人和团体。加入本集团向Person.GroupsOwned。如果我Person对象从存储库回来,GroupsOwned等于初始群体,然而,当我拿到小组回来,如果我检查Group.Admins计数,计数为0。加入表具有组ID和是PersonID保存在它。
When I run my integration test, basically I'm creating a new person and group. Adding the Group to the Person.GroupsOwned. If I get the Person Object back from the repository, the GroupsOwned is equal to the initial group, however, when I get the group back if I check count on Group.Admins, the count is 0. The Join table has the GroupID and the PersonID saved in it.
感谢您的任何建议。
推荐答案
的事实它增加了两个记录表看起来像你缺少一个的。因为两者的人及该组被改变,NHibernate的是持续的关系两次(一次对每个对象)。逆属性是专门为避免这种
The fact that it is adding two records to the table looks like you are missing an inverse attribute. Since both the person and the group are being changed, NHibernate is persisting the relation twice (once for each object). The inverse attribute is specifically for avoiding this.
我不知道如何在代码中添加映射,但链接展示了如何做到这一点的XML。
I'm not sure about how to add it in mapping in code, but the link shows how to do it in XML.
这篇关于连贯NHibernate多到多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!