首先在实体框架代码中定义外键

时间:2016-11-07 17:08:53

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

在下面的模型示例中(取自此official ASP.NET site),我了解他们正在定义Blogs(父)和Posts(子)表之间的外键关系。但是在下面的Blog类中,public List<Post> Posts { get; set; }属性的用途是什么?如果我从此模型中删除此属性并生成SQL Server数据库,我仍然可以看到在BlogId表中使用Posts成功创建数据库作为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; }
    }
}

1 个答案:

答案 0 :(得分:3)

南,

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

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

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

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

相关问题