[英]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.