使用一对多关系插入新/更新现有记录

ins*_*ide 6 .net c# asp.net entity-framework dbcontext

我有两个简单的模型,我在实体框架的帮助下从中创建数据库表:

public class Blog 
{ 
    public int Id { get; set; } 
    public string Title { get; set; } 
    public virtual ICollection<Post> Posts { get; set; } 

    public Blog() 
    {
        Posts = new Collection<Post>();
    }
} 

public class Post 
{ 
    public int Id { get; set; } 
    public string Title { get; set; } 
    public string Content { get; set; } 
    // foreign key of Blog table
    public int BlogId { get; set; } 
}
Run Code Online (Sandbox Code Playgroud)

现在在我的数据库上下文中,我有 DBSet 来生成数据库表:

public DbSet<Blog> Blogs { get; set; }
Run Code Online (Sandbox Code Playgroud)

数据库表按预期生成,但现在的问题是,如何将带有帖子的新博客插入数据库。我试过这样的事情:

Blog blog = context.Blogs.FirstOrDefault(b => b.Title == blogTitle);

// no blog with this title yet, create a new one
if (blog == null) {
    blog = new Blog();
    blog.Title = blogTitle;

    Post p = new Post();
    p.Title = postTitle;
    p.Content = "some content";

    blog.Posts.Add(p);
    context.Blogs.Add(blog);
} 
// this blog already exist, just add post to it 
else 
{
    Post p = new Post();
    p.Title = postTitle;
    p.Content = "some content";
    context.Blogs.FirstOrDefault(b => b.Title == blogTitle).Posts.Add(p);
}

context.SaveChanges();
Run Code Online (Sandbox Code Playgroud)

如您所见,我没有涉及 Id 和 BlogId,因为它们应该由 EntityFramework 自动生成。

但是,使用此代码,只有我的博客被插入到数据库中,下次我将尝试执行相同的代码时,它会告诉我我博客的 Posts 集合是空的。

难道我做错了什么?是否有更好的做法来将记录插入/更新到具有一对多关系的数据库?

谢谢

更新:

多亏了答案,我能够将博客和帖子都插入到我的数据库中,但是,我的帖子仍然没有链接到特定的博客,帖子表中的 BlogId 始终为 0。

我需要手动增加它还是某种属性?

小智 3

尝试添加

public Blog Blog { get; set; }
Run Code Online (Sandbox Code Playgroud)

用于发布和配置的属性

          modelBuilder.Entity<Post >().HasRequired(n => n.Blog)
            .WithMany(n=>n.Posts )
            .HasForeignKey(n => n.BlogId)
            .WillCascadeOnDelete(true);
Run Code Online (Sandbox Code Playgroud)

在上下文定义中的 OnModelCreating(DbModelBuilder modelBuilder) 中

然后重新生成数据库