我在一个项目中使用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> {
}
我想要的是在同一张表中同时拥有CheeseCake
和VanillaCheeseCake
。 Cake.CakeType
可以用作判别器。我也尝试将VanillaCheeseCakeMap
定义为CakeMap
的ClassMap,但是nhibernate没有找到ID的映射?
答案 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());
}
}