Fluent NHibernate 多对多 [英] Fluent NHibernate Many-to-Many

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

问题描述

我正在使用 Fluent 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();

组:...

 HasManyToMany<Person>(x => x.Admins)
    .WithTableName("GroupAdministrators")
    .WithParentKeyColumn("GroupID")
    .WithChildKeyColumn("PersonID")
    .Cascade.SaveUpdate();

当我运行我的集成测试时,基本上我是在创建一个新的人和组.将组添加到 Person.GroupsOwned.如果我从存储库中取回 Person 对象,GroupsOwned 等于初始组,但是,如果我检查 Group.Admins 上的计数,当我取回组时,计数为 0.Join 表具有 GroupID 和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 将关系持久化两次(每个对象一次).inverse 属性专门用于避免这种情况.

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.

这篇关于Fluent NHibernate 多对多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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