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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With