code -first实体框架 - 继承和导航属性是否可行?

时间:2016-06-21 21:52:12

标签: c# entity-framework ef-code-first

我还没能把这个想出来。

public abstract class A
{
    public int property1 { get; set; }
    public int property2 {get; set; }
}

public class B : A
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public IList<C> C { get; set; }

}

public class C : A
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int AId { get; set; }

    public int dummyproperty {get; set; }

    public int BId { get; set; }

    [ForeignKey("BId")]
    public virtual B B { get; set; }
}

如何让我的数据库上下文使用这些B和C类构建这两个表?

1 个答案:

答案 0 :(得分:0)

class Program
    {
        static void Main(string[] args)
        {
            var context = new MyContext();
            foreach(var b in context.Bs)
            {
                Console.WriteLine(b.ToString());
            }
        }
    }

    public class MyContext : DbContext
    {
        public DbSet<C> Cs { get; set; }
        public DbSet<B> Bs { get; set; }
    }

然后在Package Manager Console中运行命令: 启用的迁移 add-migration初始 更新的数据库

然后在文件&#39; Configuration.cs&#39;中添加B和C的一些记录。方法种子。