Entity Framework从子属性获取SUM

问题描述 投票:1回答:1

我有以下模型,我想为OrderTotalType(枚举)为“ total”或99的客户的所有订单获取所有OrderTotalItems的总和:

public class Customer
{
    ...
    public ICollection<Order> Orders { get; set; } = new Collection<Order>();
}

public class Order
{
    ...
    public ICollection<OrderTotalItem> OrderTotalItems { get; set; } = new Collection<OrderTotalItem>();
}

public class OrderTotalItem
{
    [Required]
    public int Id { get; set; }
    [Required]
    [Column(TypeName = "decimal(10, 4)")]
    public decimal Value { get; set; }
    [Required]
    public OrderTotalType Type { get; set; }
}

我正在建立一个CustomerAdminDTO以包括管理客户端的客户的所有相关数据:

public class CustomerAdminDto
{
    public int Id { get; set; }
    public string UserId { get; set; }
    public Gender Gender { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string VATId { get; set; } = "";
    public bool VATIdValid { get; set; } = false;
    public DateTime Added { get; set; }
    public DateTime LastModified { get; set; }
    public decimal OrdersTotal { get; set; }
    public CustomerStatusShortDto CustomerStatus { get; set; }
    public CustomerAddressDto CustomerAddress { get; set; }
    public CustomerAddressDto BillingAddress { get; set; }
    public ICollection<OrderListShortDto> Orders { get; set; }
}

在我的数据服务中,我这样填写DTO

var customerAdmin = await _context.Customers
    .Include(x => x.Addresses)
    .Include(x => x.CustomerStatus)
    .Include(x => x.Orders)
        .ThenInclude(x => x.OrderTotalItems)
    .Where(x => x.UserId == userid)
    .Select(customer => new CustomerAdminDto 
    {
        Id = customer.Id,
        UserId = customer.UserId,
        Gender = customer.Gender,
        FirstName = customer.FirstName,
        LastName = customer.LastName,
        VATId = customer.VATId,
        VATIdValid = customer.VATIdValid,
        Added = customer.Added,
        LastModified = customer.LastModified,
        OrdersTotal = customer.Orders.Sum(x => x.OrderTotalItems
            .Where(x => x.Type == Enums.OrderTotalType.Total)
            .Sum(x => x.Value)),
        CustomerStatus = new CustomerStatusShortDto
        {
            Id = customer.CustomerStatus.Id,
            Name = customer.CustomerStatus.Name,
        },
    ...
    }
    .FirstOrDefaultAsync();

除了OrdersTotal以外,一切正常。

API编译正常,但在运行时引发以下错误:

Microsoft.Data.SqlClient.SqlException(0x80131904):无法对包含聚合或子查询的表达式执行聚合函数。

感谢您的提示!

c# entity-framework entity-framework-core
1个回答
1
投票

无法对包含聚集或子查询的表达式执行聚集功能。

[SQL Server中的此错误表示您试图在其他包含聚合函数(您的情况为customer.Orders.Sum())的表达式上调用聚合函数(您的情况为.Sum(x => x.Value))。为了避免这种情况,您可以简化OrdersTotal的LINQ表达式:

OrdersTotal = customer.Orders.SelectMany(o => o.OrderTotalItems).Where(x => x.Type == Enums.OrderTotalType.Total).Sum(x => x.Value)

这里只有一个聚合,因此应该可以正常工作

© www.soinside.com 2019 - 2024. All rights reserved.