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;