实体框架:删除子实体 [英] Entity Framework: Removing child entity

查看:176
本文介绍了实体框架:删除子实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从新闻中删除类别对象,但不起作用

I am trying to remove category object from News but it doesn't work

我的代码如下所示:

var OriginalCategoriesIds = db.News.Where(w => w.NewsId == 1)
                                   .SelectMany(v => v.Categories)
                                   .ToList();
News NewsToUpdate = new News() { NewsId = 1 };
db.News.Attach(NewsToUpdate);

foreach (var category in OriginalCategoriesIds)
{
    if (!model.SelectedCategoriesIds.Contains(category.CategoryId))
    {
        NewsToUpdate.Categories.Remove(category);
    }
}

db.SaveChanges();


推荐答案

EF应该足够聪明,以查看您更新的实体并根据哪些存在,知道要删除哪些。而不是检查哪些不属于,请检查哪些。理论上应该适当地同步。另外,很可能你也想检查那些不在那里的那些。而不是从新闻中加载现有的类别ID,只需加载所有附加的ID,然后将其全部添加。

EF should be smart enough to look at your updated entity and know which ones to remove based on which ones are present. Instead of checking which ones don't belong anymore, check which ones do. In theory it should properly sync up then. Also, most likely you also want to check which ones were added that weren't there. Instead of loading existing category ids from the news, just load all the ids that are now attached and then add them all in.

   News NewsToUpdate = new News() { NewsId = 1 };
   var updatedCategoryIds = model.SelectedCategoriesIds;
   NewsToUpdate.Categories.AddRange(db.Categories.Where(c => updatedCategoryIds.Contains(c.CategoryId));
   db.News.Attach(NewsToUpdate);
   db.SaveChanges();

这篇关于实体框架:删除子实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆