【发布时间】:2021-11-02 14:35:52
【问题描述】:
我有三个实体,第一个是Product:
public class Product
{
public Guid Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public DateTime CratedDate { get; set; } = DateTime.Now;
public ApplicationUser ApplicationUser { get; set; }
public string ApplicationUserId { get; set; }
public ProductCategory ProductCategory { get; set; }
public Guid ProductCategoryId { get; set; }
public string ProductType { get; set; }
}
第二个实体是Users:
public class ApplicationUser : IdentityUser
{
public string DisplayName { get; set; }
public decimal Balance { get; set; }
public virtual IEnumerable<Product> Products { get; set; }
public virtual IEnumerable<Order> Orders { get; set; }
}
第三个实体是Order:
public class Order
{
public Guid Id { get; set; }
public Product Product { get; set; }
public Guid ProductId { get; set; }
public ApplicationUser User { get; set; }
public string UserId { get; set; }
public DateTime OrderDate { get; set; }
}
我尝试使用以下代码获取订单并按用户分组并获取产品总价:
var orders = _db.Orders.GroupBy(x => x.User.UserName)
.Select(x => new
{
userName = x.Key,
toolsCount = x.Count(),
totalPrice = x.Sum(s => s.Product.Price)
})
.ToList();
但我收到此错误:
System.InvalidOperationException:LINQ 表达式 'GroupByShaperExpression:
KeySelector:a.UserName,
ElementSelector:EntityShaperExpression:
实体类型:订单
值缓冲区表达式:
ProjectionBindingExpression: EmptyProjectionMember
IsNullable: 假.Sum(s => s.Product.Price)' 无法翻译。以可翻译的形式重写查询,或通过插入对“AsEnumerable”、“AsAsyncEnumerable”、“ToList”或“ToListAsync”的调用显式切换到客户端评估。请参阅https://go.microsoft.com/fwlink/?linkid=2101038 了解更多信息。 )
【问题讨论】:
-
出于好奇,如果你:
.GroupBy(x =>x.User.UserName, x => x.Product.Price)并将totalPrice = x.Sum(s=>s.Product.Price)交换为totalPrice = x.Sum()是否有效? -
干得好,谢谢
标签: c# entity-framework asp.net-core