Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
451 views
in Technique[技术] by (71.8m points)

c# - fluent nhibernate - many-to-many relationship mapping on same entity

I am having a problem trying to map out a many-to-many relationship , where both sides of the relationship reference the same entity. I am using Fluent NHibernate and NH3.1.

Basically, the scenario is this - I have a category, which can have multiple parents. Thus, a category has multiple other categories as parents, as well as multiple other categories as its children.

HasManyToMany(x => x.ParentCategories).AsBag().Table("parentcategorychildren").ParentKeyColumn("ChildID").ChildKeyColumn("ParentID").Cascade.SaveUpdate();
HasManyToMany(x => x.ChildrenCategories).AsBag().Table("parentcategorychildren").ParentKeyColumn("ParentID").ChildKeyColumn("ChildID").Inverse();

However, when I try to build the factory, I get the following error:

The relationship Category.ChildrenCategories to Category.ChildrenCategories has Inverse specified on both sides. Remove Inverse from one side of the relationship.

What I am finding strange is why is it mentioning 'Category.ChildrenCategories' to Category.ChildrenCategories, as opposed to ParentCategories?

Any help would be greatly appreciated !

I just created a bounty for this, because it's important enough to me. Please, I'm not interested in "you can't do this" as an answer.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is most likely a FNH bug and it is most likely already fixed in the latest FNH source code. There is no problem when using FNH1.0 and NH2.1. Equivalent HBM mapping works well in FNH1.2 and NH3.1:

<bag name="ParentCategories" cascade="all" table="parentcategorychildren">
    <key column="ChildID" />
    <many-to-many column="ParentID" class="Category" />
</bag>

<bag name="ChildrenCategories" inverse="true" table="parentcategorychildren">
    <key column="ParentID" />
    <many-to-many column="ChildID" class="Category" />
</bag>

EDIT: After digging in FNH source code I found a workaround. Let's say, your configuration looks like this:

.Mappings(m => {
    m.FluentMappings.AddFromAssemblyOf<Category>();
})

The unlucky code can be suppressed by this configuration:

.Mappings(m => {
    var persistenceModel = new PersistenceModel();
    persistenceModel.AddMappingsFromAssembly(typeof(Category).Assembly);
    persistenceModel.ValidationEnabled = false; // this makes the trick
    m.UsePersistenceModel(persistenceModel);
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...