【发布时间】:2014-07-04 01:00:36
【问题描述】:
我首先在编写 EF 代码,我喜欢抽象!所以想要这样的 ItemCat 实体:
public abstract class EntityBase
{
public int Id { get; set; }
}
public abstract class TreeBase : EntityBase
{
public int? ParentId { get; set; }
public string Name { get; set; }
public virtual TreeBase Parent { get; set; }
public virtual ICollection<TreeBase> Children { get; set; }
}
public abstract class CatBase : TreeBase
{
public string ImageUrl { get; set; }
public string Description { get; set; }
public int OrderId { get; set; }
}
public class ItemCat : CatBase
{
public stringName { get; set; }
// other fields...
public virtual ICollection<Item> Items { get; set; }
}
我的地图 startgey 是每个类型的表格。TPT
ItemCat 的所有基类都被 abstract 关键字修饰。但是在迁移中我得到了 Db 中的 TreeBases 表,真的是为什么?我很奇怪,因为它是抽象的。我的映射是否需要明确定义任何配置?我正在使用 EF 6
Edit 迁移中的 EF 也为 TreeBase 表创建鉴别器列,当我插入 Record 时它具有 ItemCat 值。
编辑
protected override void OnModelCreating(DbModelBuilder mb)
{
//Item
mb.Configurations.Add(new TreeBaseConfig());
mb.Configurations.Add(new CatConfig());
}
public class TreeBaseConfig:EntityTypeConfiguration<TreeBase>
{
public TreeBaseConfig()
{
HasMany(rs => rs.Children).WithOptional(rs => rs.Parent).HasForeignKey(rs => rs.ParentId).WillCascadeOnDelete(false);
}
}
public class CatConfig : EntityTypeConfiguration<CatBase>
{
public CatConfig()
{
//properties
Property(rs => rs.Name).IsUnicode();
Property(rs => rs.ImageUrl).IsUnicode();
Property(rs => rs.Description).IsUnicode();
}
}
编辑
我添加了 ItemCatConfig 类:
public ItemCatConfig()
{
//map
Map(m => { m.ToTable("ItemCats"); m.MapInheritedProperties(); });
}
但得到:
类型“ItemCat”无法按定义映射,因为它映射 从使用实体拆分或其他类型的继承属性 继承的形式。要么选择不同的继承映射 策略,以便不映射继承的属性,或更改所有类型 映射继承属性和不使用拆分的层次结构。
【问题讨论】:
-
您能发布您的派生 DbContext 类的代码,或者至少发布 OnModelCreating 方法吗?
-
嗨@joelmdev 是的,为什么不
-
你有什么想法,我很困惑,可能是什么问题?
-
恕我直言,“问题”是 EF 默认策略是 TPH。如果要启用 TPT,则必须为类型显式配置表名。
-
您的 ItemCatConfig 中有
ToTable("Cats")吗?
标签: c# entity-framework orm