我有枚举:
public enum CmdType {
[Display(Name = "abc")]
AbcEnumIdentifier = 0,
[Display(Name = "xyz")]
XyzEnumIdentifier = 1,
...
}
我想将每个枚举的名称获取到我的查询中,但即使使用 .WithTranslations()
我也会收到此错误:
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.
查询:
var joinedRecord =
(
from m in mTable
join b in bTable on m.Id equals b.aRefId
select new {
aId = a.Id,
aAttrib1 = a.Attrib1
...
bCmdType = Enum.GetName(typeof(CmdType), b.CmdType)
}
).WithTranslations();
如何在查询中使用 Enum.GetName(...)
返回生成的值?
最佳答案
LINQ to entities 尝试将您的查询转换为 SQL 但未能成功,因为在 SQL 中没有等效的 Enum.GetName
方法。
您需要具体化查询结果并将枚举值转换为它们在内存中的名称。
var joinedRecords = (
from m in mTable
join b in bTable on m.Id equals b.aRefId
select new {
aId = a.Id,
aAttrib1 = a.Attrib1
...
bCmdType = b.CmdType
}
).AsEnumerable() //Executes the query, further you have simple CLR objects
.Select(o => new {
aId = o.Id,
aAttrib1 = o.Attrib1
...
bCmdTypeName = Enum.GetName(typeof(CmdType), o.CmdType)
});
关于c# - 将 Enum.GetName(...) 合并到 Linq 查询中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34230502/