LINQ 数据排序

LINQ Data Sorting

我正在尝试从 JQuery ajax 调用中填充 select 标记选项。我正在使用 Asp.Net Core 2.1 Razor Pages 和 PostgreSQL 作为数据库。

这是我的服务器端 LINQ 代码

[HttpGet]
public ActionResult TypeofAccounts()
{
    var result = (from N in _POSContext.TypeOfAccounts
                  select new { label = N.AccountType, id = N.AccountType });

    return Json(result);
}

它工作正常。现在,我想从 LINQ 中对这些结果进行排序,所以我尝试了以下方法,但它总是遇到 Npgsql 异常 "column \"label\" does not exist"

var result = (from N in _POSContext.TypeOfAccounts.OrderBy(x=>x.AccountType)
              select new { label = N.AccountType, id = N.AccountType });         

var result = (from N in _POSContext.TypeOfAccounts
              select new { label = N.AccountType, id = N.AccountType }).OrderBy(x => x.label);        

var result = (from N in _POSContext.TypeOfAccounts.OrderBy(x => x.AccountType)
               where N.AccountType != null
               select new { label = N.AccountType, id = N.AccountType });

我可以看到生成的 sql 中缺少列。

{SELECT x."AccountType" AS id
FROM "TypeOfAccounts" AS x
WHERE x."AccountType" IS NOT NULL
ORDER BY label}

你可以试试这个

var result = _POSContext.TypeOfAccounts
                .Where(x => x.AccountType != null)
                .OrderBy(x => x.AccountType)
                .ToList()
                .Select(x => 
                    new
                    {
                        label = x.AccountType,
                        id = x.AccountType
                    }
                );

您需要使用 ToList 方法从数据库调用查询,然后选择您的对象,如下所示:

var result = _POSContext.TypeOfAccounts
            .Where(x => x.AccountType != null)
            .OrderBy(x => x.AccountType)
            .ToList()
            .Select(x => 
                new
                {
                    label = x.AccountType,
                    id = x.AccountType
                }
            );