两个子类映射到同一个表

时间:2014-08-28 09:49:43

标签: inheritance nhibernate fluent-nhibernate

我在一个项目中使用Fluent NHibernate并遇到一个我无法自行解决的问题:

class Cake {}
class CheeseCake : Cake {}
class VanillaCheeseCake : CheeseCake {}


class CakeMap :  Class<Cake> {
    Table("CAKE");
    Id(x => x.Id, "ID")
    .GeneratedBy.GuidComb();
    Map(x => x.CakeType);
}

class CheeseCakeMap :  Subclass<CakeMap> {
    Table("CHEESE_CAKE");
    KeyColumn("ID");
    Map(x => x.CheeseAmount);
}

class VanillaCheeseCakeMap :  Subclass<CheeseCakeMap> {

}

我想要的是在同一张表中同时拥有CheeseCakeVanillaCheeseCakeCake.CakeType可以用作判别器。我也尝试将VanillaCheeseCakeMap定义为CakeMap的ClassMap,但是nhibernate没有找到ID的映射?

1 个答案:

答案 0 :(得分:0)

我会更改架构,使所有蛋糕类型都有一个表,并在caketype列上进行区分,但以下内容适用于您的建议:

public enum CakeType
{
    Cake,
    CheeseCake,
    VanillaCheeseCake
}

public class Cake
{
    public virtual Guid Id { get; set; }
    public virtual CakeType Type { get; protected set; }
}
public class CheeseCake : Cake
{
    public virtual int CheeseAmount { get; set; }
}
public class VanillaCheeseCake : CheeseCake
{
}

public class CakeMap : ClassMap<Cake>
{
    public CakeMap()
    {
        Table("CAKE");
        Id(x => x.Id, "ID").GeneratedBy.GuidComb();
        Map(x => x.Type, "CakeType").ReadOnly();

        DiscriminateSubClassesOnColumn("CakeType");
    }
}
public class CheeseCakeMap : SubclassMap<CheeseCake>
{
    public CheeseCakeMap()
    {
        DiscriminatorValue(CakeType.CheeseCake.ToString());

        Join("CHEESE_CAKE", join =>
        {
            join.KeyColumn("ID");
            join.Map(x => x.CheeseAmount);
        });
    }
}

public class VanillaCheeseCakeMap : SubclassMap<VanillaCheeseCake>
{
    public VanillaCheeseCakeMap()
    {
        DiscriminatorValue(CakeType.VanillaCheeseCake.ToString());
    }
}