Get result function in LINQ without translate to store expression

前端 未结 2 1581
野的像风
野的像风 2020-11-30 15:49

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

相关标签:
2条回答
  • 2020-11-30 15:57

    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.

    0 讨论(0)
  • 2020-11-30 16:07

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

    0 讨论(0)
提交回复
热议问题