3

I need to get result from a function that it need to run in LINQ query. This result bind to grid but in run time I encounter with this error:

LINQ to Entities does not recognize the method 'System.String GetName(System.Type, System.Object)' method, and this method cannot be translated into a store expression.

This is my Code:

public IQueryable GetForRah_CapacityList(XQueryParam param)
{
    var result = (from x in Data()
                  select new
                  {
                      Rah_CapacityId = x.Rah_CapacityId,
                      Rah_CapacityName = x.Rah_CapacityName,
                      Rah_St = Enum.GetName(typeof(Domain.Enums.CapacityState), x.Rah_St),
                      Rah_LinesId = x.Rah_LinesId
                  }).OrderByDescending(o => new { o.Rah_CapacityId });
    return result;
}
Salah Akbari
  • 38,126
  • 10
  • 70
  • 102
Sasan Karimi
  • 507
  • 3
  • 20

2 Answers2

6

GetName couldn't be translated to T-SQL, Linq to Entities couldn't recognize it. You can modify the code as below:

 var result = (from x in Data().AsEnumerable()
              select new
              {
                  Rah_CapacityId = x.Rah_CapacityId,
                  Rah_CapacityName = x.Rah_CapacityName,
                  Rah_St = Enum.GetName(typeof(Domain.Enums.CapacityState), x.Rah_St),
                  Rah_LinesId = x.Rah_LinesId
              }).OrderByDescending(o => new { o.Rah_CapacityId });

With .ToList() after data is loaded, any further operation (such as select) is performed using Linq to Objects, on the data already in memory.

EDIT: Also your method's return type is IQueryable while your query is IOrderedEnumerable of anonymous type, so you should either change the method's type to System.Object or as a better solution create a class, send the values into the class's properties, and then return it.

Salah Akbari
  • 38,126
  • 10
  • 70
  • 102
2

You can't use this method in Linq-To-Entities because LINQ does not know how to translate Enum.GetName to sql. So execute it in memory with Linq-To-Objects by using AsEnumerable and after the query use AsQueryable to get the desired AsQueryable:

So either:

var result = Data()
             .OrderBy(x=> x.CapacityId)
             .AsEnumerable()
             .Select(x => new
             {
                  Rah_CapacityId = x.Rah_CapacityId,
                  Rah_CapacityName = x.Rah_CapacityName,
                  Rah_St = Enum.GetName(typeof(Domain.Enums.CapacityState), x.Rah_St),
                  Rah_LinesId = x.Rah_LinesId
             })
             .AsQueryable();

You should first use OrderBy before you use AsEnumerable to benefit from database sorting performance. The same applies to Where, always do this before AsEnumerable(or ToList).

Tim Schmelter
  • 429,027
  • 67
  • 649
  • 891