R – Fluent NHibernate Automapping Bi-directional relationships

fluent-nhibernatenhibernate

I am trying to automap my domain model using fluent nhibernate. In this particular case I have a bidirectional one-to-many relationship that i need to map. Problem is that it doesn't automatically realize it as a bidirectional relation but as two different relations altogether and creates a separate foreign key for each.

How do I tell fluent nhibernate that it is the same relation? I hope i am being clear enough.

Best Answer

You can override the automap using the 1.0RC. Try this example from SharpArchitecture's bi-directional mapping from Employee to Territory, where Territory is the inverse of the relationship:

   public class EmployeeMap : IAutoMappingOverride<Employee>
     {
        public void Override(AutoMap<Employee> mapping) {

        //... other omitted mappings...

        mapping.HasManyToMany<Territory>(x => x.Territories)
            .WithTableName("EmployeeTerritories")
            .WithParentKeyColumn("EmployeeID")
            .WithChildKeyColumn("TerritoryID")
            .AsBag();
    }
}

   public class TerritoryMap : IAutoMappingOverride<Territory>
{
    public void Override(AutoMap<Territory> mapping) {

        //... other omitted mappings...

        mapping.HasManyToMany<Employee>(x => x.Employees)
            .WithTableName("EmployeeTerritories")
            .Inverse()
            .WithParentKeyColumn("TerritoryID")
            .WithChildKeyColumn("EmployeeID")
            .AsBag();
    }
}
Related Topic