Use a derived class in fluent nHibernate

2020-07-22 19:37发布

问题:

I have two tables which share common fields. Rather than re-map all of these I would like to have a base class with the common fields. For POCO this is simple:

class Base
{
   public string commonField {get;set;}
}
class Derived : Base
{
   public string specificField {get;set;}
}
class OtherDerived : Base
{
   public string specificOtherField {get;set;}
}

Note that there is no such thing as a table for "base". It just holds lots of common fields shared among several tables. Yes, I know this is not well normalized, but it's what I have to work with.

My question is - is there a way to implement this in fluent nHibernate without having to duplicate the code that maps those common properties?

回答1:

You can inherit from ClassMap to do this. I would do something like the following:

public class BaseMap<T> : ClassMap<T> where T : Base
{
    public BaseMap()
    {
        Map(x => x.commonField, "COMMON_FIELD");
    }
}

public class DerivedMap : BaseMap<Derived>
{
    public DerivedMap()
    {
        Table("DERIVED_TABLE");
        Polymorphism.Explicit();  //You may want to use this in your case.
        Map(x => x.DerivedField, "DERIVED_FIELD");
    }
}

Notice the Polymorphism.Explicit(); above. In your case I think you are going to want this.

http://www.nhforge.org/doc/nh/en/#mapping-declaration-class