C# – nHibernate (w/ Castle ActiveRecord) with C# interfaces (esp for DTO’s)

asp.netccastle-activerecorddtonhibernate

Any using nHibernate with a Domain object & DTO object implemented from a common interface? I'm trying to separate all of my nHibernate attributes into the Domain object, leaving my DTO's and interface clean.

The problem comes with nHibernate throwing errors when it tries to associate the interfaces with the concrete classes.

NHibernate.MappingException: Association references unmapped class: IContact

I understand why its complaining about the use of the non-hibernated interface, but I'm struggling to visual a way to restructure around it. A skeleton reproduction of my code is set out as below, any ideas for how to structure my code better?

public interface ICompany
{
    IList<IContact> Contacts { get; set; }
}

public class CompanyDTO : ICompany
{
    private IList<IContact> contacts;
    public IList<IContact> Contacts { get { return this.contacts; } set { this.contacts = value; } }

}

[ActiveRecord]
public class Company : ActiveRecordBase<Company>, ICompany
{
    private IList<IContact> contacts;
    [HasMany(Inverse=true, Table="Contact", ColumnKey="CompanyId")] 
    [ScriptIgnore]
    public IList<IContact> Contacts { get { return this.contacts; } set { this.contacts = value; } }
}

Edit:

I want to have a common interface so that I can ensure they are keeping the same fields (ie. leaning on the compiler to keep them consistent). It also allows me to use the DTO's in the view part of my application, but casts them to domain objects for business and data access.
Also, alex's solution does not work because ICompany's Contacts is of type IList, not IList. I would like to keep it as IContact so my DTO object has no knowledge of the Contact Domain object.

Best Answer

In your concrete case you should just add Type = typeof(Contact) to the mapping attribute, like so:

[HasMany(Inverse=true, Table="Contact", ColumnKey="CompanyId", Type=typeof(Contact))]