Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# EF6实体集合的插入或更新_C#_Entity Framework_Insert Update - Fatal编程技术网

C# EF6实体集合的插入或更新

C# EF6实体集合的插入或更新,c#,entity-framework,insert-update,C#,Entity Framework,Insert Update,我有下一个代码: using (var context = new DataContext()) { var dbHistoryItems = context.Set<HistoryItem>(); var historyItems = history as HistoryItem[] ?? history.ToArray(); var historyItemIds = historyItems.Select(c => c.Id); var

我有下一个代码:

using (var context = new DataContext())
{
    var dbHistoryItems = context.Set<HistoryItem>();

    var historyItems = history as HistoryItem[] ?? history.ToArray();
    var historyItemIds = historyItems.Select(c => c.Id);

    var existingEntities = dbHistoryItems.Where(h => historyItemIds.Contains(h.Id));
    if (existingEntities.Any())
    {
        var newEntities = historyItems.Where(h => !existingEntities.Select(e => e.Id).Contains(h.Id));
        dbHistoryItems.AddRange(newEntities);   
    }
    context.SaveChanges();
}

似乎EF没有检测到数组元素内的更改。但是,您可以强制更新。选中此项

您不会更改任何属性。
history
从何而来,您希望发生哪些更新?否,“history是输入参数列表”并没有说明这一点。这是一个分离的实体,例如通过MVC表单POST?什么是“EF不检测数组元素内的更改”的意思?另外,如果您认为某个问题在别处得到了回答,请标记为重复。@CodeCaster对于examle,sql类型
varbinary
将是EF中的
byte[]
。更改数组中的某些元素
byte[]
并调用
SaveChanges
不会检测到数组内容已更改,也不会更新。没错,您必须在实体上重新分配一个
byte[]
属性,或显式将其标记为已修改,以便更改跟踪器拾取该更改,但我真的不明白这与这里的问题有什么关系。@CodeCaster可能是OP没有对相关代码提出问题。问题中的代码与insert相关,而问题是关于更新的。
foreach(var item in collection)
{
   db.AddOrUpdate(item);
}
db.SaveChanges;