【问题标题】:Map TPT Strategy Entity Framework Code fist图TPT策略实体框架代码拳头
【发布时间】: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


【解决方案1】:

当您不执行任何 ToTable() 映射时,您使用了 TPH(按层次结构表),在同时执行 ToTable()MapInheritedProperties() 时使用了 TPC(按具体类型的表)。如果您想使用 TPT(每个类型的表),请仅执行 ToTable() 映射并关闭对 MapInheritedProperties() 的调用,如下所示:

ToTable("ItemCats");

【讨论】:

  • 好的,现在它使用 owns 属性创建 itemCat 和 TreeBase 表。我只想要ItemCat
  • 当我使用 TPC 时必须在最后一个 Concreat 类型中映射所有基本道具:这意味着必须删除 catConfig 并在 ItemCatConfig 中使用它的映射?
  • 我强烈建议您阅读本系列,以便了解您真正想要的映射策略:weblogs.asp.net/manavi/archive/2010/12/24/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-02
  • 1970-01-01
相关资源
最近更新 更多