Can Fluent NHibernate's AutoMapper handle Inte

2019-07-31 16:51发布

问题:

I typed this simplified example without the benefit of an IDE so forgive any syntax errors. When I try to automap this I get a FluentConfigurationException when I attempt to compile the mappings -

"Association references unmapped class IEmployee."

I imagine if I were to resolve this I'd get a similar error when it encounters the reference to IEmployer as well. I'm not opposed to creating a ClassMap manually but I prefer AutoMapper doing it instead.

public interface IEmployer 
{ 
  int Id{ get; set; } 
  IList<IEmployee> Employees { get; set; } 
} 

public class Employer: IEmployer 
{ 
  public int Id{ get; set; } 
  public IList<IEmployer> Employees { get; set; } 
  public Employer() 
  { 
    Employees = new List<IEmployee>(); 
  } 
} 

public interface IEmployee 
{ 
  int Id { get; set; } 
  IEmployer Employer { get; set; } 
} 

public class Employee: IEmployee 
{ 
  public int Id { get; set;} 
  public IEmployer Employer { get; set;} 
  public Employee(IEmployer employer) 
  { 
    Employer = employer; 
  }
}

I've tried using .IncludeBase<IEmployee>() but to no avail. It acts like I never called IncludeBase at all.

Is the only solution to either not use interfaces in my domain entities or fall back on a manually defined ClassMap?

Either option creates a significant problem with the way my application is designed. I ignored persistence until I had finished implementing all the features, a mistake I won't be repeating again :-(

回答1:

It's not a restriction imposed by Fluent or its AutoMapper, but by NHibernate itself.

I therefore don't think you'd get there with the manual class map. You'll have to lose the interfaces in the property and list definitions. You can keep the interfaces, but mapped properties and collections must use the concrete types of which NHibernate knows.



回答2:

public class PersonMap : ClassMap<Person>
{
    public PersonMap()
    {
        Id(x => x.Id);
        Map<Address>(x => x.Address); // Person.Address is of type IAddress implemented by Address
    }
}