【问题标题】:Defining Foreign Key in Entity Framework Code First首先在实体框架代码中定义外键
【发布时间】:2016-11-07 17:08:52
【问题描述】:

在以下模型示例(取自 official ASP.NET site)中,我知道他们正在定义 Blogs(父)和 Posts(子)表之间的外键关系。但是在下面的 Blog 类中,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; }
    }
}

【问题讨论】:

标签: c# entity-framework asp.net-core foreign-key-relationship entity-framework-core


【解决方案1】:

南,

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

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

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

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

【讨论】:

  • 其实EfCore还不支持延迟加载,你必须使用Include。为了澄清 FK 是基于 BlogId 创建的,Posts 属性只是一个导航属性。
  • @VivienChevallier 所以你的查询是说给我所有posts of which blog?或者,您的查询是说给我每个博客以及与每个博客关联的所有帖子。换句话说,这是在 Blogs 和 Posts 表之间编写 LINQ JOIN 的另一种方式。在将其标记为 Answer 之前,我正在尝试了解您的回复。
  • @nam 我的查询是:给我每个博客以及与每个博客关联的所有帖子。
  • @VivienChevallier 如果没有在 Blog 类中使用的属性 public List&lt;Post&gt; Posts { get; set; },此查询将无法工作?
  • 没错,你写不出来。
猜你喜欢
  • 2012-04-09
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
  • 2016-09-25
  • 1970-01-01
  • 2013-09-01
  • 1970-01-01
  • 2011-05-08
相关资源
最近更新 更多