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

本文关键字:更新 字典 扩展 何使用 EntityFramework | 更新日期: 2023-09-27 18:20:18

我正在尝试使用以下代码更新一个表

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] });

无法创建类型为的常量值'System.Collections.Generic.KeyValuePair`2[[System.Int32,mscorlib,版本=4.0.0.0,文化=中性,PublicKeyToken=b77a5c561934e089],[System.Decimal,mscorlib,版本=4.0.0.0,区域性=中性,PublicKeyToken=b77a5c561934e089]]'。此中仅支持基元类型或枚举类型上下文

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

问题是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方法来保存所有更改。