Inheritance Mapping with Fluent NHibernate

后端 未结 4 2135
既然无缘
既然无缘 2020-12-04 18:15

Given the following scenario, I want map the type hierarchy to the database schema using Fluent NHibernate.

I am using NHibernate 2.0


Type Hier

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-04 19:02

    I know this is really old, but it is now pretty simple to set up fluent to generate the exact mapping you initially desired. Since I came across this post when searching for the answer, I thought I'd post it.

    You just create your ClassMap for the base class without any reference to your subclasses:

    public class ItemMap : ClassMap
    {
        public ItemMap()
        {
            this.Table("Item");
            this.DiscriminateSubClassesOnColumn("ItemType");
            this.Id(x => x.ItemId, "ItemId");
            this.Map(x => x.FieldA, "FieldA");
        }
    }
    

    Then map your abstract subclass like this:

    public class SubItemMap: SubclassMap
    {
        public SubItemMap()
        {
            this.Map(x => x.FieldB);
        }
    }
    

    Then map your concrete subclasses like so:

    public class ConcreteItemXMap : SubclassMap
    {
        public ConcretItemXMap()
        {
            this.Join("ConcreteItemX", x =>
            {
                x.KeyColumn("ItemID");
                x.Map("FieldC")
            });
        }
    }
    

    Hopefully this helps somebody else looking for this type of mapping with fluent.

提交回复
热议问题