EF COde First Table Per Type设置,包含对基类的列表引用

时间:2013-03-08 20:46:14

标签: entity-framework ef-code-first table-per-type

我首先使用每种类型的表设置ef代码。请参阅以下结构。我们的想法是将继承的类信息存储在自己的表中,同时派生类可以引用父类和也从BaseClass派生的子类列表。

public class BaseClass
{
    public long Id {get;set;}
    public string EntityType { get; set; }
}

public class A_Class : BaseClass
{
     public string A_Property {get;set;}
     public BaseClass Parent {get; set;}
     public IList<BaseClass> Children { get; set; }
}

public class B_Class : BaseClass
{
     public string B_Property {get;set;}
     public BaseClass Parent {get; set;}
     public IList<BaseClass> Children { get; set; }
}

知道如何为模型设置DbContext吗?

1 个答案:

答案 0 :(得分:0)

要生成3个表,您可以使用API​​:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<BaseClass>().ToTable("BaseClass");
    modelBuilder.Entity<A_Class>().ToTable("AClass");
    modelBuilder.Entity<B_Class>().ToTable("BClass");

    base.OnModelCreating(modelBuilder);
}

TableAttribute

[Table("BaseClass")]
public class BaseClass
{
    public int Id { get; set; }
    public string EntityType { get; set; }
}

[Table("AClass")]
public class A_Class : BaseClass
{
    public string A_Property { get; set; }
    public BaseClass Parent { get; set; }
    public ICollection<BaseClass> Children { get; set; }
}

[Table("BClass")]
public class B_Class : BaseClass
{
    public string B_Property { get; set; }
    public BaseClass Parent { get; set; }
    public ICollection<BaseClass> Children { get; set; }
}