EntityFramework Extended how to update using values in a dictionary

c# entity-framework entity-framework-6 linq linq-to-entities

Question

Using the following code, I'm attempting to update a 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.

1
1
11/3/2015 2:18:19 PM

Accepted Answer

The issue is that your dictionary instance cannot be converted to SQL notation by EF. You may only use a primitive type collection or an enumeration type collection, as stated in the exception. Do the projection first to get the keys in order to prevent this problem, and then express your inquiry.

 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();

I'm not sure how the implementation ofUpdate method, which I suppose is a custom extension method, but I want to caution you that Linq is meant for consulting data, not for changing it.foreach to each individual returned by the query in order to alter them, and then I call theSaveChanges a way to preserve all the modifications.

0
11/3/2015 4:00:31 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow