繁体   English   中英

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

[英]code -first Entity framework - Is this possible with inheritance and navigation properties?

我无法弄明白这一点。

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类构建这两个表?

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中,运行命令:enable-migrations add-migration初始更新数据库

然后在文件'Configuration.cs'方法Seed中添加B和C的一些记录。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM