我在EF核心中拥有一类Post和PostCategory的相关实体。
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public virtual ICollection<PostCategory> PostCategory { get; set; }
}
public class PostCategory
{
public int Id { get; set; }
public string Title {get;set;}
}
当我更新帖子时,我从视图中建立了与该帖子相关的一组新类别,当我添加新类别时很好-它们被添加到数据库中,但是如果我从列表中删除类别,则现有记录从PostCategory表中删除?
var newCats = new List<PostCategory>();
var allcats = _context.PostCategory.GroupBy(o => new { o.Title }).Select(x => x.FirstOrDefault()).ToList();
foreach (var cat in allcats) {
string key = Request.Form["PostCat_" + cat.Id];
if (key != "false") {
newCats.Add(cat);
}
}
var post = postViewModel.Post;
post.PostCategory = newCats;
_context.Update(post);
_context.SaveChanges();