在 LINQ 中获取结果函数而不转换为存储表达式 [英] Get result function in LINQ without translate to store expression

查看:24
本文介绍了在 LINQ 中获取结果函数而不转换为存储表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从需要在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆