Search code examples
c#entity-frameworklinqlinq-to-entities

Get result function in LINQ without translate to store expression


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;
}

Solution

  • 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).