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; } }
With the mapping looking like this
Person: ...
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();
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.
Thanks for any advice you may have.
Fluent NHibernate offers an alternative to NHibernate's standard XML mapping files. Rather than writing XML documents, you write mappings in strongly typed C# code. This allows for easy refactoring, improved readability and more concise code.
NHibernate is an ORM (Object Relational Mapper). Its purpose is to map objects in your OO application to tables in a database for persistence. Why would you need it? Because it can save you from writing a lot of tedious ADO.NET code.
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.
@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With