实体框架 有效地添加和删除集合中的项



我有一个带有子集合的实体

给定一个 id 列表 => NewIdList 我想从不在 NewIdList 中的子项中创建新项

,并为那些在 NewIdList 中但不在子项中的 id 创建新项。

借口伪代码:)

myEntity.Children = new [] {2, 3}
var newIdList = new [] {1, 2, 4, 5}
// Do Magic
myEntity.Children = new [] {1, 2, 4, 5}
// Note that '2' would not have a created date 
// or audit record as it was in the list before Do Magic occured

我打算做这样的事情

var newIdList = new [] {1, 2, 4, 5};
var childrenToRemove = myEntity.Children.Where(c=> !newIdList.Contains(c));
var childrenToAdd = newIdList.Where(c => myEntity.Children.Contains(c));
foreach(var cr in childrenToRemove){
    myEntity.Children.Remove(cr);
}
foreach(var ca in childrenToAdd ){
    myEntity.Children.Add(cr);
}

这是实现这一目标的最佳方法吗?感觉有点笨拙

var list1 = new[] { 2, 3 };
var list2 = new[] { 1, 2, 4, 5 };
var excepts = list1.Except(list2);
var union = list1.Union(list2);
var newlist = union.Except(excepts);
Console.WriteLine(string.Join(",", newlist));

最新更新