簡體   English   中英

首先在實體框架代碼中定義外鍵

[英]Defining Foreign Key in Entity Framework Code First

在下面的模型示例中(取自這個官方的ASP.NET站點 ),我了解他們正在定義Blogs (父級)和Posts (子級)表之間的外鍵關系。 但是在下面的Blog類中,使用public List<Post> Posts { get; set; } public List<Post> Posts { get; set; } public List<Post> Posts { get; set; }財產? 如果我刪除此屬性並從此模型中生成SQL Server數據庫,我仍然可以看到在Posts表中使用BlogId成功創建數據庫作為Blog表的外鍵

namespace EFGetStarted.AspNetCore.NewDb.Models
{
    public class BloggingContext : DbContext
    {
        public BloggingContext(DbContextOptions<BloggingContext> options)
            : base(options)
        { }

        public DbSet<Blog> Blogs { get; set; }
        public DbSet<Post> Posts { get; set; }
    }

    public class Blog
    {
        public int BlogId { get; set; }
        public string Url { get; set; }

        public List<Post> Posts { get; set; }
    }

    public class Post
    {
        public int PostId { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }

        public int BlogId { get; set; }
        public Blog Blog { get; set; }
    }
}

南,

如果您需要直接從Blog對象的實例訪問Posts ,則Blog類中的Posts屬性可能很有用。

加載帖子可以通過延遲加載或使用Include方法加載Entity Framework Eager來完成:

    var blogs1 = context.Blogs 
                      .Include(b => b.Posts) 
                      .ToList(); 

如果刪除它將不會阻止正確創建數據庫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM