我正在为调度日历加载ServiceTrips
,并想知道是否有最快的方法来急切地从多个表中加载相关数据。
这是需要加载的模型(映射是每个具体类型的表)
public class ServiceTrip : BaseEntity
{
public ICollection<Employee> Crew { get; set; }
public ICollection<ServiceAssignment> Assignments { get; set; }
}
public class ServiceAssignment : BaseEntity
{
public ServiceOrder ServiceOrder { get; set; }
public DeliveryOrder DeliveryOrder { get; set; }
}
public class ServiceOrder : OrderBase { }
public class DeliveryOrder : OrderBase { }
public abstract class OrderBase : BaseEntity
{
public ICollection<ServiceAssignment> Assignments { get; set; }
public Sale Sale { get; set; }
}
public class Sale : BaseEntity
{
public Employee Manager { get; set; }
public Customer Customer { get; set; }
public ICollection<ServiceOrder> ServiceOrders { get; set; }
public ICollection<DeliveryOrder> DeliveryOrders { get; set; }
}
public class Employee : BaseEntity { }
public class Customer : BaseEntity { }
public abstract class BaseEntity
{
public int Id { get; set; }
public string Name { get; set; }
}
我基本上尝试过这样的事情,不知道从哪里开始。
var tripsQuery = db.ServiceTrips
.Where(x => x.StartDate >= FirstDay && x.StartDate <= LastDay)
.Include(x => x.Crew)
.Include(x => x.ServiceAssignments)
.Include(x => x.ServiceAssignments.Select(y => y.DeliveryOrder))
.Include(x => x.ServiceAssignments.Select(y => y.ServiceOrder))
.Include(x => x.ServiceAssignments.Select(y => y.DeliveryOrder.Sale))
.Include(x => x.ServiceAssignments.Select(y => y.ServiceOrder.Sale))
.Include(x => x.ServiceAssignments.Select(y => y.DeliveryOrder.Sale.Customer))
.Include(x => x.ServiceAssignments.Select(y => y.ServiceOrder.Sale.Customer))
.Include(x => x.ServiceAssignments.Select(y => y.DeliveryOrder.Sale.Manager))
.Include(x => x.ServiceAssignments.Select(y => y.ServiceOrder.Sale.Manager))
;
该问题简化了模型。在制作中,我从大约20张桌子开始。加载大约需要10-15秒。我尝试异步加载每天,但这增加了加载的总时间。
答案 0 :(得分:1)
在我看来,当你发出一个连接20个表的复杂查询时,你可能想要开始检查数据库本身
以下是一些指导原则(有些要点与SQL Server相关,我自由地假设它是您正在使用的数据库)
检查原始SQL上的查询执行计划 - 如果在SQL中重现整个EF代码非常耗时,可能只是其中的一部分 - 例如ServiceTrips,ServiceAssignments和DeliveryOrder表。这将让您了解索引等方面的瓶颈
检查由于数据的大小,网络延迟是否是瓶颈而不是查询本身
考虑使用可能会提高效果的indexed views
架构 - 为了加速这种复杂的查询,可以使用某种缓存来存储相关数据 - 在您的情况下可能是管理员的名字,船员等。