firebird
firebird

Reputation: 3511

LINQ to Entities does not recognize the method, how to fix

I have the following query:

var query = (from e in conn.equipments
             select new 
             {
                  id = e.id,
                  status = GetEquipmentStatusText(e.status)
             }).ToList();

public static string GetEquipmentStatusText(int status) {
   return (status == 1) ? "Active" : "Not Active";
}

This results in the error:LINQ to Entities does not recognize the method

How do I fix it in a way that the "GetEquipmentStatusText" can be centralized into a method where it can be called in other LINQ queries?

Upvotes: 0

Views: 125

Answers (1)

Habib
Habib

Reputation: 223187

Just don't use that method call instead inline your condition.

status = e.status == 1 ? "Active" : "Not Active"

LINQ to EF would try to convert your LINQ expression to under laying data source language (probably SQL), and since SQL doesn't have any knowledge of your method it would fail.

You can execute your query without that method and then execute your method on in-memory collection. like:

var query = (from e in conn.equipments
             select new 
             {
                  id = e.id,
                  status = e.status
             }).AsEnumerable(); //as Servy pointed out

var result = (from e in query 
             select new 
             {
               id = e.id, 
               status = GetEquipmentStatusText(e.status)
             }).ToList();

Upvotes: 3

Related Questions