簡體   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