在LINQ中获取结果函数而无需转换为存储表达式 [英] Get result function in LINQ without translate to store expression
问题描述
我需要从需要在LINQ查询中运行的函数中获取结果.此结果绑定到网格,但是在运行时我遇到此错误:
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无法识别方法'System.String GetName(System.Type,System.Object)'方法,并且此方法不能为 转换为商店表达式.
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.
这是我的代码:
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;
}
推荐答案
您不能在Linq-To-Entities中使用此方法,因为LINQ不知道如何将Enum.GetName
转换为sql.因此,使用AsEnumerable
在Linq-To-Objects中在内存中执行它,并在查询后使用AsQueryable
获得所需的AsQueryable
:
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
:
所以:
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();
在使用AsEnumerable
之前,应首先使用OrderBy
,以受益于数据库排序性能. Where
同样如此,请始终在AsEnumerable
(或ToList
)之前执行此操作.
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
).
这篇关于在LINQ中获取结果函数而无需转换为存储表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!