在 Entity Framework 代码优先中定义外键

Defining Foreign Key in Entity Framework Code First

在下面的模型示例中(取自 official ASP.NET site)我知道他们正在定义 Blogs(父级)和 Posts(子级)之间的外键关系 table秒。但是在Blogclass下面public List<Post> Posts { get; set; }属性有什么用呢?如果我删除此 属性 并从此模型生成 SQL 服务器数据库,我仍然可以看到数据库已成功创建 BlogId in Posts table as Foreign Blog table

的关键
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; }
    }
}

南,

如果您需要直接从 [=12= 实例访问帖子,Blog class 中的 Posts 属性 可能会有用] 对象。

可以通过延迟加载或 Entity Framework 使用 Include 方法进行预加载来加载帖子:

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

如果删除它不会阻止正确创建数据库。