1
votes

I am trying to update a table using following code

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 Answers

0
votes

The problem is EF can't translate your dictionary instance to sql notation. As the exception said, you can only use a primitive type collection or an enumeration type collection. To avoid this issue do the projection first to obtain the keys and then declare your query:

 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 don't know how is implemented the Update method, I guess is a custom extension method, but I want to warn you that Linq is used for consult data, not to modify them, that's way I use in my code a foreach to modify each person returned by the query, and at the end I call the SaveChanges method to save all the changes.