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

标签 c# entity-framework linq enums

我有枚举:

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/

相关文章:

c# - 多客户端服务器 - 2 路连接的常用方式

c# - LINQ:选择在列表中只出现一次的元素

c# - 导航属性 'UId' 不是类型 'Users' 的声明属性

sql - 如何执行左联接并排除与 LINQ 中的子查询匹配的结果?

c# - 使用 Entity Framework 是否可以创建一个未映射到我的数据库表上的实体?

c# - 将 Stylecop 集成到 Jenkins 的 .NET 项目中

c# - 如何欺骗更新身份列?

linq-to-sql - Entity Framework : Auto-updating foreign key when setting a new object reference

c# - 用于比较的订单日期列表

c# - 在 Lambda 语法中绕过 int.TryParse 的 else block