在 Entity Framework Core 中,可以使用 FromSqlRaw 方法执行原始 SQL 查询,然后使用 Select 方法将结果转换为指定的 DTO。

以下是一个示例:

  1. 定义 DTO 类
public class OrderDto
{
    public int Id { get; set; } 
    public string CustomerName { get; set; } 
    public decimal TotalAmount { get; set; } 
}
  1. 执行 SQL 查询并转换为 DTO
var orders = dbContext.Orders
    .FromSqlRaw('SELECT Id, CustomerName, SUM(Amount) AS TotalAmount FROM Orders GROUP BY Id, CustomerName')
    .Select(o => new OrderDto
    {
        Id = o.Id,
        CustomerName = o.CustomerName,
        TotalAmount = o.TotalAmount
    })
    .ToList();

在上面的代码中,我们首先使用 FromSqlRaw 方法执行原始 SQL 查询,然后使用 Select 方法将结果转换为指定的 DTO 类型。在 SQL 查询中,我们使用 GROUP BY 子句聚合订单总金额,并将其作为 TotalAmount 属性返回给 DTO 类型。最后,我们使用 ToList 方法将结果集转换为列表并返回。

Entity Framework Core: 使用 SQL 查询并聚合转换为 DTO

原文地址: https://www.cveoy.top/t/topic/j0LU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录