LINQ to Entities does not recognize the method "Newtonsoft.Json.Linq.JToken get_Item (System.String)",

The following code works:

string data = Encoding.UTF8.GetString(eventData.GetBytes()); JObject o = JObject.Parse(data); var disp = db.Dispositivos .Where(p => p.ClaveDispositivo == "UM5WOkRIFtS9dWbM5f1YM/ncpdrpSYrh3zND9Y/YHM4="); if(disp.ToList().Count > 0) { // ... 

However, when I try to use a variable instead of a hard coded value:

 string data = Encoding.UTF8.GetString(eventData.GetBytes()); JObject o = JObject.Parse(data); var disp = db.Dispositivos .Where(p => p.ClaveDispositivo == o["deviceKey"].ToString()); if(disp.ToList().Count > 0) { // ... 

I get this error:

LINQ to Entities does not recognize the Newtonsoft.Json.Linq.JToken get_Item (System.String) method.

+5
source share
3 answers

The message is clear enough. The expression passed to your Where call is later translated into SQL using EF. EF has no idea how to translate a property indexer to a JToken , so it fails.

You can get around this by getting a value outside the expression. Linking this in your lambda will result in a "constant" in the generated expression.

 var deviceKey = o["deviceKey"].ToString(); var disp = db.Dispositivos .Where(p => p.ClaveDispositivo == deviceKey); 

Alternatively, you'd better call disp.Any() (or replace Where with Any ) if that's all you want to check. Calling ToList will cause all data to be retrieved and materialized only so that it can be ignored.

+10
source

The problem is very well described by the exception message. The basic structure of an entity can not translate it to SQL (LINQ to entity is converted to ESQL)

The solution is to call .ToList() before using Where

PS Yes, I know that this is not very pleasant, because it will load everything into memory.

+1
source

use delegate:

 var disp = db.Dispositivos.Where(delegate(Dispositivos p) { return p.ClaveDispositivo == o["deviceKey"].ToString(); }); 
0
source

All Articles