Fluent NHibernate Many-to-Many

雨燕双飞 提交于 2019-11-28 19:19:46
Santiago Palladino

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.

I'm not sure about how to add it in mapping in code, but the link shows how to do it in XML.

emeryc

@Santiago I think you're right.

The answer might just be that you need to remove one of your ManyToMany declarations, looking more at Fluent it looks like it might be smart enough to just do it for you.

Are you making sure to add the Person to the Groups.Admin? You have to make both links.

You have three tables right?

People, Groups, and GroupAdministrators

when you add to both sides you get

People (with an id of p1) Groups (with an id of g1)

and in GroupAdministrators you have two columns and a table that has

(p1,g1)

(p1,g1)

and your unit test code looks like the following.

Context hibContext //Built here
Transaction hibTrans //build and start the transaction.

Person p1 = new Person()
Groups g1 = new Groups()

p1.getGroupsOwned().add(g1)
g1.getAdmins().add(p1)

hibTrans.commit();
hibContext.close();

And then in your test you make a new context, and test to see what's in the context, and you get back the right thing, but your tables are all mucked up?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!