Use a derived class in fluent nHibernate

青春壹個敷衍的年華 提交于 2019-12-06 08:37:09

问题


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



来源:https://stackoverflow.com/questions/12154583/use-a-derived-class-in-fluent-nhibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!