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

user2962228 picture user2962228 · Nov 6, 2013 · Viewed 7.2k times · Source

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.

Answer

Habib picture Habib · Nov 6, 2013

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