【问题标题】:Entity Framework Add and Remove items in collection efficiently实体框架有效地添加和删除集合中的项目
【发布时间】:2013-11-14 14:18:37
【问题描述】:

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

给定一个 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);
}

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

【问题讨论】:

    标签: c# entity-framework-5


    【解决方案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));
    

    【讨论】:

    • 哦,我明白了,这没有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-28
    • 2014-08-21
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多