加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 将Enum.GetName(…)合并到Linq Query中

发布时间:2020-12-15 04:20:58 所属栏目:百科 来源:网络整理
导读:我有枚举: public enum CmdType { [Display(Name = "abc")] AbcEnumIdentifier = 0,[Display(Name = "xyz")] XyzEnumIdentifier = 1,...} 我想将每个枚举的名称放入我的查询中,但即使使用.WithTranslations()我也会收到此错误: LINQ to Entities does not
我有枚举:
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(…)返回生成的值?

解决方法

您正在调用无法转换为SQL的Enum.GetName(typeof(CmdType),b.CmdType),因为如果您查看行,您将看到有一个int而不是有问题的枚举值的名称.

试试这个:

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 = b.CmdType
    }
)
.AsEnumerable() // or ToList()
.Select( // map to another type calling Enum.GetName(typeof(CmdType),b.CmdType) )
.WithTranslations();

这样做是通过调用AsEnumerable()或ToList(),您不再处理IQueryable< T>的实例. (这是你的原始查询返回的,坏的一面一旦你这样做,所有返回的对象将在内存中).因此,一旦在内存中有对象,就可以像使用任何其他C#对象一样使用它们,这些对象应该允许您使用所需的方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读