在下面的模型示例中(取自此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; }
}
}
答案 0 :(得分:3)
南,
如果您需要直接从Posts
对象的实例访问帖子,Blog
类中的Blog
属性可能很有用。
加载帖子可以通过延迟加载或使用Include方法加载Entity Framework Eager来完成:
var blogs1 = context.Blogs
.Include(b => b.Posts)
.ToList();
如果删除它将不会阻止正确创建数据库。