gpt4 book ai didi

c# - 在 linq 中添加带有计数函数的额外列以进行查询?

转载 作者:太空宇宙 更新时间:2023-11-03 20:54:51 27 4
gpt4 key购买 nike

我正在处理一个 Asp.net Core 项目并使用 CodeFirst 并使用这样的 sql 语法进行查询

  SELECT PartID, PartName, PartLevel,
(SELECT COUNT(ID) AS Expr1
FROM dbo.systemparts
WHERE(MSys.PartID = PartLevel)) AS ChildCount
FROM dbo.systemparts AS MSys

示例输出

sample output sql statment

我的模型

public class SystemPart
{
[Key]
public int PartID { get; set; }

public string PartName { get; set; }

public int PartLevel { get; set; }
}

Controller

public class HomeController : Controller
{

private readonly ApplicationDbContext _context;

public HomeController(ApplicationDbContext context)
{
_context = context;
}

public IActionResult Index()
{
return View();
}
}

现在,我想在 linq 中更改它以在索引操作中查询字符串或 lambda 表达式。但我无法处理 ChildCount 字段。我该怎么做?

最佳答案

您通常会为此定义一个 ViewModel,因为您希望将它返回到 View :

public class SystemPartViewModel
{
public int PartId { get; set; }
public string PartName { get; set; }
public int PartLevel { get; set; }
public int ChildCount { get; set; }
}

然后您可以使用 LINQ 轻松地进行查询:

public async Task<IActionResult> Index()
{
var query =
from msys in _context.SystemParts
let childCount = _context.SystemParts.Count(x => x.PartLevel == msys.PartID)
select new SystemPartViewModel
{
PartId = msys.PartID,
PartName = msys.PartName,
PartLevel = msys.PartLevel,
ChildCount = childCount
};

return View(await query.ToListAsync());
}

关于c# - 在 linq 中添加带有计数函数的额外列以进行查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51547990/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com