Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 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 method 'Newtonsoft.Json.Linq.JToken get_Item(System.String)' method.

like image 789
gina Avatar asked Aug 25 '16 15:08

gina


2 Answers

The message is fairly self-explanatory. The expression passed into your Where call is later translated to SQL by EF. EF has no idea how to translate a property indexer on a JToken, so it fails.

You can work around this by getting the value outside the expression. Referencing this in your lambda will result in a 'constant' in the created expression.

var deviceKey = o["deviceKey"].ToString();

var disp = db.Dispositivos
    .Where(p => p.ClaveDispositivo == deviceKey);

As an aside, you'd be better off calling disp.Any() (or replacing Where with Any) if that's all you want to check. Calling ToList will result in all the data being retrieved and materialised only for it to be ignored.

like image 54
Charles Mager Avatar answered Oct 23 '22 04:10

Charles Mager


The problem is very well described by the message of the exception. Basicaly entity framework cant translate it to SQL (LINQ to entities is transformed to ESQL)

The solution is to call .ToList() before you use Where

P.S. Yes, i know it is not very nice, because it will load everything into memory.

like image 33
Alex Avatar answered Oct 23 '22 03:10

Alex