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