我正在尝试使用 Giveaway.Giveable 来接受 Giveable 的任何子类,但由于 Giveable 是一个抽象基类,它实际上并没有被映射。我使用每个层次结构的表而不是 TPT。
我正在包括帮助其他用户的课程,并提供更多 NHibernate 的真实示例,请原谅所有代码。
例外:Giveaway 表中的关联指的是未映射的类:Giveable
AutoMap.AssemblyOf<Giveaway>(cfg).UseOverridesFromAssemblyOf<UserMappingOverride>()
.Conventions.Add(
PrimaryKey.Name.Is(x => "ID"),
DefaultLazy.Always(),
DefaultCascade.Delete(),
DynamicInsert.AlwaysTrue(),
DynamicUpdate.AlwaysTrue(),
OptimisticLock.Is(x => x.Dirty()),
ForeignKey.EndsWith("ID")))).ExposeConfiguration(BuildSchema)
public abstract class Giveable
{
ISet<Giveaway> giveaways;
public Giveable() : base()
{
giveaways = new HashedSet<Giveaway>();
}
public virtual ISet<Giveaway> Giveaways
{
get { return giveaways; }
set { giveaways = value; }
}
public virtual int ID { get; set; }
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
var toCompareWith = obj as Giveable;
return toCompareWith != null && ((ID == toCompareWith.ID));
}
public override int GetHashCode()
{
int toReturn = base.GetHashCode();
toReturn ^= ID.GetHashCode();
return toReturn;
}
}
public class Giveaway
{
ISet<Entry> entries;
public Giveaway() : base()
{
entries = new HashedSet<Entry>();
CreatedDate = DateTime.UtcNow;
}
public virtual DateTime CreatedDate { get; private set; }
public virtual DateTime? EndDate { get; set; }
public virtual ISet<Entry> Entries
{
get { return entries; }
set { entries = value; }
}
public virtual Giveable Giveable { get; set; }
public virtual int ID {get;set;}
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
var toCompareWith = obj as Giveaway;
return toCompareWith != null && ((ID == toCompareWith.ID));
}
public override int GetHashCode()
{
int toReturn = base.GetHashCode();
toReturn ^= ID.GetHashCode();
return toReturn;
}
}
public class GiveableMappingOverride : IAutoMappingOverride<Giveable>
{
public void Override(AutoMapping<Giveable> mapping)
{
mapping.DiscriminateSubClassesOnColumn("GiveableType");
mapping.Map(x => x.Name).Length(200).Not.Nullable();
mapping.Map(x => x.ImageName).Length(200).Nullable();
mapping.Map(x => x.ReleaseDate).Not.Nullable();
mapping.HasMany(x => x.Giveaways)
.Fetch.Select()
.AsSet()
.Inverse()
.LazyLoad();
}
}
public class GiveawayMappingOverride : IAutoMappingOverride<Giveaway>
{
public void Override(AutoMapping<Giveaway> mapping)
{
mapping.Map(x => x.ThingID).Length(20).Nullable();
mapping.Map(x => x.Text).Length(2000).Not.Nullable();
mapping.Map(x => x.CreatedDate).Not.Nullable();
mapping.Map(x => x.Platform).Not.Nullable();
mapping.Map(x => x.Type).Not.Nullable();
mapping.HasMany(x => x.Entries);
mapping.References(x => x.Giveable).Not.Nullable();
mapping.References(x => x.User).Not.Nullable();
mapping.References(x => x.Winner);
}
}