我有以下型号:
public class User
{
public long Id { get; set; }
public string? Name { get; set; }
public string? Surname { get; set; }
public string? PhoneNumber { get; set; }
public IEnumerable<Sale>? Sales { get; set; }
}
public class Product
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public IEnumerable<Sale>? Sales { get; set; }
}
public class Sale
{
public int Id { get; set; }
public User? User { get; set; }
public List<SaleItem> SaleItems { get; set; }
public DateTime CreatedDt { get; set; }
}
public class SaleItem
{
public int Id { get; set; }
public Sale? Sale { get; set; }
public Product? Product { get; set; }
public int Count { get; set; }
}
需要获得按客户和产品分组的计数和价格。
我试图用下面的方法解决这个问题:
var list = await context.SaleItems
.Include(x => x.Product)
.Include(x => x.Sale).ThenInclude(x => x.User)
.Select(x => new
{
UserId = x.Sale.User.Id,
UserName = x.Sale.User.Name,
ProductId = x.Product.Id,
ProductName = x.Product.Name,
TotalCount = x.Count,
TotalPrice = x.Product.Price * x.Count
})
.GroupBy(x => new { x.UserId, x.ProductId })
.SelectMany(x => x)
.ToListAsync();
但它不工作。谢谢!
2条答案
按热度按时间vfhzx4xs1#
SelectMany
在这里是错误运算符您也可以删除Includes,因为不需要它们qmb5sa222#
SelectMany()
将返回列表的列表的查询扁平化。使用
.Select(x => x)
而不是.SelectMany(x => x)
。您可以查看Difference Between Select and SelectMany以获得更详细的说明。