gpt4 book ai didi

c# - 将 Enum.GetName(...) 合并到 Linq 查询中

转载 作者:太空狗 更新时间:2023-10-29 21:08:18 37 4
gpt4 key购买 nike

我有枚举:

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/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com