插入 new/Update 个具有一对多关系的现有记录

Insert new/Update existing record with one to many relationship

我有两个简单的模型,我在 Entity Framework 的帮助下从中创建数据库 tables:

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; } 
}

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

public DbSet<Blog> Blogs { get; set; }

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

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();

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

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

我是不是做错了什么?对具有一对多关系的数据库执行 insertion/update 条记录是否有更好的做法?

谢谢

更新:

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

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

应该是这样的:

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;
    blog.Posts = new Collection<Post>();
    context.Blogs.Add(blog);
} 

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

context.SaveChanges();

此外 我会删除构造函数中的 Posts 初始化

尝试添加

public Blog Blog { get; set; }

属性 到 Post 并配置

          modelBuilder.Entity<Post >().HasRequired(n => n.Blog)
            .WithMany(n=>n.Posts )
            .HasForeignKey(n => n.BlogId)
            .WillCascadeOnDelete(true);

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

然后重新生成数据库