Search code examples
mysqlnhibernatefluent-nhibernatefluentfluent-nhibernate-mapping

Fluent many-to-many relationship not working


I'm using the Fluent automapper to create a configuration for a code-first NHibernate project (MySql config) and I'm having a problem implementing efficient many-to-many relationships. As an example, let's say I want a table of Stores and a table of Employees. An employee may work at multiple stores and of course each store has multiple employees working there. So I give the Store entity a list of employees like so:

public class Store
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual IList<Employee> Employees { get; set; }

    public Store()
    {
        this.Employees = new List<Employee>();
    }
}

public class Employee
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
}

Creating this database results in the store and employee tables being automatically created but no table that maps between the two. I can create both of those entity types, add employees to the store's Employee list and save it without encountering an error, but trying to reload it results in the list being empty. However, if I add a list of stores to the employee record like this...

public class Employee
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual IList<Store> Stores { get; set; } // <----

    public Employee()
    {
        this.Stores = new List<Store>();
    }
}

... and populate the Stores list as well with the Employee entities then a storestoemployees table appears in the db and everything works fine.

It seems to me to be inefficient to require all many-to-many relationships in my application to require lists in both Entities in cases where they only need to appear in one, both in the Entity declation itself and in all the code that now has to add things twice. Is there something I'm doing wrong here, or is there a way for me to override whatever default mapping Fluent is doing?


Solution

  • With one collection FNH can not decide wether to use one-to-many or many-to-many and will default to one-to-many. You can selectivly override this with an override.

    AutoMap.Assembly...
        .Override<Store>(m => m.HasManyToMany(s => s.Employees).Table("store_to_employee"));