插入具有一对多关系的新/更新现有记录

时间:2015-08-19 14:57:41

标签: c# asp.net .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; } 
}

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

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

数据库表按预期生成,但现在问题是,如何将新帖博客添加到数据库中。我尝试过这样的事情:

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自动生成。

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

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

谢谢

更新:

感谢答案,我能够将Blog和Post都插入到我的数据库中,但是,我的帖子仍然没有链接到特定的Blog,Post表中的BlogId总是为0.

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

2 个答案:

答案 0 :(得分:2)

尝试添加

public Blog Blog { get; set; }

要发布和配置的属性

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

在上下文定义中的OnModelCreating(DbModelBuilder模型构建器)

然后重新生成数据库

答案 1 :(得分:1)

应该是这样的:

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

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