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

时间:2013-11-14 04:42:30

标签: c# entity-framework-5

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

给出一个ids =>列表NewIdList我想要来自不在NewIdList中的Children的项目,并为NewIdList中但不在Children中的那些id创建新项目。

借口Psuedo代码:)

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);
}

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

1 个答案:

答案 0 :(得分:1)

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));