【发布时间】:2022-07-21 16:12:10
【问题描述】:
我有以下型号:
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();
但它不起作用。 谢谢!
【问题讨论】:
-
“但它不起作用” - 如何它不起作用?您是否收到运行时错误?编译错误?出乎意料的结果?
-
你为什么打电话给
.SelectMany( x => x )?这违背了GroupBy的观点。 -
还有EF,指定哪个版本。