3

I have a problem. I create a Data Entity Model in Visual Studio. And in Linq;

Guid RtuDataId = db.RtuData.Where(x => x.CommunicationUnit.Id == new Guid(ID))
    .OrderByDescending(x => x.ReadOn)
    .LastOrDefault().Id;

I get error ;

does not recognize the method ... method, and this method cannot be translated into a store expression.

I searched in Google but I don't understand this error.

Servy
  • 202,030
  • 26
  • 332
  • 449
user2962228
  • 41
  • 1
  • 3

1 Answers1

7

Its LastOrDefault which is not supported in LINQ to Entites. I am not sure why you are using OrderByDescending, instead you can use OrderBy and then select First. Also its better if you create new Guid before your query and then pass it to your where clause like:

var guid = new Guid(ID);
Guid RtuDataId = db.RtuData
                   .Where(x => x.CommunicationUnit.Id == guid)
                   .OrderBy(x => x.ReadOn)
                   .FirstOrDefault()
                   .Id;

Since FirstOrDefault may return null, so you should check for null before accessing Id

Habib
  • 219,104
  • 29
  • 407
  • 436
  • Great answer, Habib. One question though: is it really any different to create the new `Guid` before the query? The reason why I ask is because it was my understanding that the `Guid` isn't actually created for each element, but rather the entire expression is translated into SQL and the `Guid` is only created once. Is this correct, or am I mistaken? – Zachary Kniebel Nov 06 '13 at 20:58
  • @ZacharyKniebel, with LINQ to Entities, yes, since it will be translated into SQL, but for Enumerables, it should be create once and then used. I was just trying to be on the safe side with regard to this. – Habib Nov 06 '13 at 21:00
  • @ZacharyKniebel It depends entirely on the query provider implementation. It could notice that you're creating an object that will be the same throughout, so it could create one and use it, it could find a way to map it into the SQL query itself so that the object-creation syntax is irrelevant, or it could just not understand what the object means in context and just throw an exception. It choose the last option. Some other query provider might choose one of the others, or even do something else entirely. – Servy Nov 06 '13 at 21:16