[英]EF Core Include childs after query with joins
我正在使用.Net Core 2.0和EF Core。 以下查詢工作正常,但不包含子級。
該查詢的作用是加入:
通過將數量(在OrderItem中)與價格(在產品中)相乘,然后求和,得出訂單總數。
現在,我想在我的Web API的最終JSON中看到“ OrderItem”和“ Product”。 因此,要獲得包含所有三個實體的最終JSON以及訂單總價的摘要。
這是我的存儲庫:
public class OrderRepository : IOrderRepository
{
private readonly BasketDbContext _basketDbContext;
public OrderRepository(BasketDbContext basketDbContext)
{
_basketDbContext = basketDbContext;
}
public Order GetOrderById(int id)
{
return (from o in _basketDbContext.Orders
join oi in _basketDbContext.OrderItems on new { o.Id } equals new { Id = oi.OrderId }
join p in _basketDbContext.Products on new { oi.ProductId } equals new { ProductId = p.Id }
where o.Id == id
group new { o, p, oi } by new
{
o.Id,
o.OrderDate
}
into g
select new Order
{
Id = g.Key.Id,
OrderDate = g.Key.OrderDate,
TotalPrice = g.Sum(p => p.p.Price * p.oi.Quantity)
})
.Include(x => x.OrderItems)
.ThenInclude(y => y.Product)
.FirstOrDefault();
}
}
方法GetOrderById中的include不起作用,但是我不知道如何在此類查詢中包括這些。
這些是我的模型:
public class Order
{
public int Id { get; set; }
public DateTime OrderDate { get; set; }
public decimal TotalPrice { get; set; }
public List<OrderItem> OrderItems { get; set; }
public decimal CalculateTotal()
{
return OrderItems.Sum(item => item.GetPrice());
}
}
public class OrderItem
{
public int Id { get; set; }
[Required(ErrorMessage = "Empty OrderId")]
public int OrderId { get; set; }
[Required(ErrorMessage = "Empty ProductId")]
public int ProductId { get; set; }
[Required(ErrorMessage = "Empty Quantity")]
[Range(1, 20, ErrorMessage = "Quantity must be between 1 to 20")]
public int Quantity { get; set; }
public Product Product { get; set; }
public decimal GetPrice()
{
return Product.Price * Quantity;
}
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
}
謝謝!
您要獲得的數據是您在查詢中選擇的數據。 即ID,OrderDate和TotalPrice:
select new Order
{
Id = g.Key.Id,
OrderDate = g.Key.OrderDate,
TotalPrice = g.Sum(p => p.p.Price * p.oi.Quantity)
})
如果要在此處映射新訂單(如id,orderDate等),則還必須逐字段映射“ ItemOrder”和“ Product”實體。
我認為您可以簡單地返回訂單,而無需在查詢中創建新訂單,例如:
return (from o in _basketDbContext.Orders where o.Id == id select o)
.Include(x => x.OrderItems)
.ThenInclude(y => y.Product)
.FirstOrDefault();
可以對返回的結果進行TotalPrice計算。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.