简体   繁体   English

LINQ 表达式“无法翻译”

[英]The LINQ expression "could not be translated"

I have migrated my application from dotNet core2.1 to Dotnet core5.我已经将我的应用程序从 dotNet core2.1 迁移到了 Dotnet core5。 The below function has stopped working.以下功能已停止工作。 I tried to debug the code but I was not able find the solution.我尝试调试代码,但找不到解决方案。 The line which is giving error is X => Convert.ToInt32(X.Value) .给出错误的行是X => Convert.ToInt32(X.Value) If I don't do the conversion function works fine but the order of list gets disturbs.如果我不这样做,转换功能可以正常工作,但列表的顺序会受到干扰。

Error :-错误:-

The LINQ expression 'DbSet<EbDepartmentMsts>()\\r\\n .OrderBy(e => Convert.ToInt32(e.DeptCode.ToString()))' could not be translated. Additional information: Translation of method 'object.ToString' failed. If this method can be mapped to your custom function, Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'

function功能

public List<SelectListItem> GetDepartmentCode()
        {
            var table = new List<SelectListItem>();
            try
            {
                table = (from eb in _context.EbDepartmentMsts

                         select new SelectListItem
                         {
                             Text = string.Concat(eb.DeptCode.ToString(), "~", eb.Description),
                             Value = eb.DeptCode.ToString()
                         }).OrderBy(X => Convert.ToInt32(X.Value)).ToList();

            }catch(Exception ex)
            {

            }
            return table;
        }

You need to materialize the LINQ query via .ToList() , then perform .Select() .您需要通过.ToList()实现 LINQ 查询,然后执行.Select()

From the existing LINQ query,从现有的 LINQ 查询,

select eb.DeptCode, eb.Description

for querying only required fields.仅用于查询必填字段。

table = (from eb in _context.EbDepartmentMsts
         select new { eb.DeptCode, eb.Description }
        )
        .ToList()
        .Select(x => new SelectListItem
        {
            Text = string.Concat(x.DeptCode.ToString(), "~", x.Description),
            Value = x.DeptCode.ToString()
        })
        .OrderBy(x => Convert.ToInt32(x.Value))
        .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM