EF 将新的多记录添加到表中
本文关键字:添加 记录 EF | 更新日期: 2023-09-27 18:31:21
上下文类这是我的上下文类。它的工作原理是在博客帖子标签表中添加帖子的 ID 和标签的 ID......但是,它会添加新的标记 ID,而不是已存储在数据库中的现有标记。
public class WebsiteDBContext : DbContext
{
public DbSet<BlogPost> BlogPosts { get; set; }
public DbSet<Tag> Tags { get; set; }
public DbSet<Author> Authors { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<BlogPost>().HasRequired(bp => bp.Author).WithMany(a => a.BlogPosts);
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<BlogPost>().HasMany(bp => bp.Tags).WithMany(t => t.Posts).Map(m =>
{
m.MapLeftKey("BlogPostID");
m.MapRightKey("TagID");
m.ToTable("BlogPostTags");
});
}
}
我想发生什么:
Tag Table BlogPostTags Table
ID Name BlogID TagID
---------------- ----------------
1 Dogs 1 1
2 Cats 1 9
3 Birds 1 11
4 Horses
5 Rabbits
6 Reptiles
7 Insects
8 Nature
9 Puppies
10 Kittens
11 Cute
12 Products
但真正发生的是它会在标签表中创建带有 ID 的新标签。这样
Tag Table BlogPostTags Table
ID Name BlogID TagID
---------------- ----------------
1 Dogs 1 13
2 Cats 1 14
3 Birds 1 15
4 Horses
5 Rabbits
6 Reptiles
7 Insects
8 Nature
9 Puppies
10 Kittens
11 Cute
12 Products
13 Dogs
14 Puppies
15 Cute
重复 名字不好! 如何解决此问题以获得预期的结果?这是我的动作结果方法
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Title,PublishDate,PublishTime,Body,AuthorID,Tags")] CreateBlogPostVM blogpost)
{
List<Tag> tags = new List<Tag>();
foreach (var tag in blogpost.Tags.Where(t => t.IsChecked == true))
{
tags.Add(new Tag { TagID = tag.TagID, Name = tag.Name });
}
if (ModelState.IsValid)
{
BlogPost newPost = new BlogPost
{
Title = blogpost.Title,
PublishDate = blogpost.PublishDate,
PublishTime = blogpost.PublishTime,
Body = blogpost.Body,
Author = db.Authors.Where(bp => bp.AuthorID == blogpost.AuthorID).Single(),
Tags = tags //Add list of tags
};
db.BlogPosts.Add(newPost);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(blogpost);
}
您需要查找数据库中已存在的现有标签,而不是添加新标签。替换此内容:
foreach (var tag in blogpost.Tags.Where(t => t.IsChecked == true))
{
tags.Add(new Tag { TagID = tag.TagID, Name = tag.Name });
}
跟:
foreach (var tag in blogpost.Tags.Where(t => t.IsChecked == true))
{
tags.Add(db.Tags.Find(tag.TagID));
}
(这假设 TagID 是标签表的主键,如果不是,您可以执行类似 tags.Add(db.Tags.Where(t=>t.TagID == tag.TagID).First())
的操作)