我有同样的问题,我的查询需要40秒.
我发现问题出在.Include("table_name")
功能上.我拥有的越多,它就越糟糕.相反,我在查询后立即将我的代码更改为Lazy Load所需的所有数据,这将总时间从40秒减少到大约1.5秒.据我所知,这完成了同样的事情.
所以对于你的代码,它将是这样的:
var groupQuery = (from g in context.Groups where g.GroupKey == 6 select g).OfType(); var groups = groupQuery.ToList(); foreach (var g in groups) { // Assuming Dealcontract is an Object, not a Collection of Objects g.DealContractReference.Load(); if (g.DealContract != null) { foreach (var d in g.DealContract) { // If the Reference is to a collection, you can just to a Straight ".Load" // if it is an object, you call ".Load" on the refence instead like with "g.DealContractReference" above d.Contracts.Load(); foreach (var c in d.Contracts) { c.AdvertiserAccountType1Reference.Load(); // etc.... } } } }
顺便提一下,如果你要在当前代码中将这行代码添加到查询之上,它会将时间缩短到大约4-5秒(在我的选项中仍然过于敏感)从我的理解,该MergeOption.NoTracking
选项禁用了很多用于更新和插入数据库的跟踪开销:
context.groups.MergeOption = MergeOption.NoTracking;