EntityFramework 扩展了如何使用字典中的值进行更新

EntityFramework Extended how to update using values in a dictionary

我正在尝试使用以下代码更新 table

Dictionary<int, decimal> myDictionary = GetDictionary();

Context.Persons
.Where(t => mydictionary.Select(s => s.Key).Contains(t.Id))
.Update(t => new Person { Salary = mydictionary[t.Id] });

Unable to create a constant value of type 'System.Collections.Generic.KeyValuePair`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Decimal, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'. Only primitive types or enumeration types are supported in this context.

问题是 EF 无法将您的字典实例转换为 sql 表示法。如异常所述,您只能使用原始类型集合或枚举类型集合。为避免此问题,请先进行投影以获取密钥,然后声明您的查询:

 var keys= mydictionary.Select(s => s.Key);
 var query=Context.Persons.Where(t => keys.Contains(t.Id));
 foreach(var person in query)
 {
   person.Salary=mydictionary[person.Id];
 }
 Context.SaveChanges();

我不知道Update方法是怎么实现的,我猜是自定义扩展方法,但我想警告你,Linq是用来查询数据的,不是用来修改数据的,就是这样我在我的代码中使用 foreach 来修改查询返回的每个人,最后我调用 SaveChanges 方法来保存所有更改。