批量更新记录Entitiy框架列表
我有一个更新对象的列表。我试图用一次数据库调用来更新所有记录(一个context.SaveChanges()命令)。该程序在Windows服务中运行。我的问题是,而不是更新我将数据库上的所有记录相乘并添加重复项。以下是我的代码。批量更新记录Entitiy框架列表
//adding the list of updated customer objects to the list
context_CLTUS.Customer_Updates.AddRange(list.customerUpdateList);
foreach (var j in list.customerUpdateList)
{
//calling entity state modify for each record
context_CLTUS.Entry(j).State = EntityState.Modified;
}
//save updated list in one db call.
context_CLTUS.SaveChanges();
我不明白为什么所有记录都是重复的而不是更新。您能否请解释并帮助我解决这个问题。谢谢。
请参阅本answer
你可以尝试以下解决方案:
交换更新操作在一个TransactionScope。
Set Configuration.AutoDetectChangesEnabled = false。
尝试Entity Framework Plus,高性能增强 库。
第一次尝试Entity Framework Plus,节省了我的时间!谢谢! – thilanka1989
@ thilanka1989对我的误解感到抱歉,在你的情况下,也许上面的评论比较容易,谢谢你的投票。 – Nico
只有你需要的东西是context_CLTUS.SaveChanges();删除其他东西 –
如果您删除了“AddRange”调用,会发生什么情况? –
删除'AddRange'为我工作感谢您的意见! – thilanka1989