gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:55:39 24 4
gpt4 key购买 nike

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

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

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

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

谢谢

更新:

感谢答案,我能够将博客和帖子都插入到我的数据库中,但是,我的帖子仍然没有链接到特定的博客,帖子表中的 BlogId 始终为 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 初始化

关于c# - 插入具有一对多关系的新记录/更新现有记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32099045/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com