获取实体框架中由子实体组成的实体
本文关键字:实体 框架 获取 | 更新日期: 2023-09-27 18:10:18
我有一些由其他实体组成的"复杂"实体。例如"订单"实体:
- 订单
- 订单详细信息(子项(
- OrderDetailsDiscount(子项的子项(
- 订单付款
- 订单状态
订单类的代码:
[MetadataType(typeof(OrderMetadata))]
public partial class Order
{
public OrderPaymentStatus PaymentStatus {
get { return Paid ? OrderPaymentStatus.Paid : OrderPaymentStatus.Pending; }
}
public bool Paid {
get {
return TotalPaid >= Total;
}
}
public decimal TotalPaid {
get {
return OrderPayments.Sum(p => p.Amount);
}
}
public decimal TotalRefund {
get {
return OrderRefunds.Sum(p => p.Amount);
}
}
public decimal TotalDebt {
get {
return Total - TotalPaid + TotalRefund;
}
}
public decimal TotalDiscounts {
get {
return ((SubTotal * DiscountPercentage) / 100) + DiscountAbsolute;
}
}
public decimal TotalSurcharges {
get {
return ((SubTotal * SurchargePercentage) / 100);
}
}
[DisplayFormat(DataFormatString="{0:C}", ApplyFormatInEditMode = false)]
public decimal Total {
get {
return SubTotal - TotalDiscounts + TotalSurcharges;
}
}
public decimal TotalTax {
get {
return (TaxEnabled) ? OrderDetails.Sum(t => t.Taxes): 0;
}
}
public decimal SubTotal {
get {
return OrderDetails.Sum(o => o.Total) + TotalTax;
}
}
public decimal DiscountOffers {
get {
return OrderDetails.Sum(o => o.DiscountOffers);
}
}
public bool HasOffers {
get {
return DiscountOffers > 0;
}
}
public decimal SurchargePercentage {
get {
return OrderSurcharges.Sum(o => o.ChargePercentage);
}
}
public decimal DiscountPercentage {
get {
return OrderDiscounts.Where(o => o.Type == (int)DiscountType.Percentage).Sum(o => o.Value);
}
}
public decimal DiscountAbsolute
{
get
{
return OrderDiscounts.Where(o => o.Type == (int)DiscountType.Absolute).Sum(o => o.Value);
}
}
}
我通常计算订单总额,所以我总是需要从一开始就加载OrderDetail.*,以避免在显示1000个订单的列表时对DB进行多次查询,所以我在我的通用存储库中实现了这种方法:
public virtual IQueryable<T> GetAllIncluding(params Expression<Func<T, object>>[] includeProperties)
{
IQueryable<T> query = Fetch();
foreach (var includeProperty in includeProperties)
{
query = query.Include(includeProperty);
}
return query;
}
我把它从我的代码中称为:
private IEnumerable<Order> GetAllOrders()
{
return unitOfWork.OrderRepository.GetAllIncluding(
o => o.OrderDiscounts,
o => o.OrderPayments,
o => o.OrderSurcharges,
o => o.OrderStates,
o => o.OrderRefunds,
o => o.OrderDetails,
o => o.OrderDetails.Select(d => d.OrderDetailDiscounts),
o => o.OrderDetails.Select(d => d.OrderDetailOffers),
o => o.User,
o => o.Employee,
o => o.Store,
o => o.TerminalSession);
}
好的。。它有效。。问题是,当我必须用这个查询其他复杂对象时,我有一个由其他子实体组成的用户实体,例如:
- 用户
- UserPoint
- 用户状态
有没有任何方法可以指示EF将一组实体作为一个整体加载,这样我就可以使用完全加载的订单和用户进行查询,以避免在请求大量记录时碰到数据库(我不想禁用延迟加载(
context.Entity.Include("ChildEntity");
或
context.Entity.Include( x => x.ChildEntity);
如果您需要更多嵌套实体
context.Entity.Include( x => x.ChildEntity.Select( c => c.ChildChildEntity ));
请记住,lambda表达式位于System.Data.Entity
命名空间中。
请记住,通常情况下,过多的联接比多个数据库调用更糟糕。