EF Core 3,优化大量Include/ThenInclude

编程入门 行业动态 更新时间:2024-10-12 16:25:37
本文介绍了EF Core 3,优化大量Include/ThenInclude的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个这样的查询

return await _ctx.Activities .Include(a => a.Attributes) .Include(a => a.Roles) .Include(a => a.Bookmarks) .Include(a => a.VideoMetas) .ThenInclude(vm => vm.Instances) .Include(a => a.ImageMetas) .ThenInclude(im => im.Instances) .Include(a => a.Procedure) .ThenInclude(p => p.Attributes) .FirstOrDefaultAsync(a => a.Id == id);

结果证明这很慢.在 EF 6 中,您可以执行 .Include(v => v.VideoMetas.Select(vm => vm.Instances) 这会更快一些(我猜,没有看过 SQL Profiler 和实际查询 tbh.我该如何优化它?我也可以使用 EF Plus 在它有 .IncludeOptimized() 但没有.ThenInclude() 的版本.我听说我可以使用 .Select 而不是 .Include() 但真的不知道如何处理在此查询中.

Which turns out to be very slow. In EF 6 you can do .Include(v => v.VideoMetas.Select(vm => vm.Instances) which is a bit faster (I guess, haven't looked at SQL Profiler and actual query tbh). How can I optimize that? I can also use EF Plus where it has .IncludeOptimized() but there is no version for .ThenInclude(). I heard I can use .Select instead of .Include() but really not sure how I can handle that in this query.

推荐答案

您需要将其拆分为多个查询,以加快性能.您可以为此使用显式加载.这不是最漂亮的解决方案,但它有效.希望 EF 5 中有更简单的解决方案.

You'll want to split it into multiple queries, to speed up the performance. You can use explicit loading for this. It's not the prettiest solution, but it works. Hopefully an easier solution will come in EF 5.

我有点猜测哪些字段是集合,哪些是正常"条目,但类似这样:

I'm guessing a bit on which fields are collections and which are "normal" entries, but something like this:

var activity = await _ctx.Activities.FindAsync(Id); await context.Entry(activity) .Collection(a => a.Attributes) .LoadAsync(); await context.Entry(activity) .Collection(a => a.Roles) .LoadAsync(); await context.Entry(activity) .Collection(a => a.Bookmarks) .LoadAsync(); await context.Entry(activity) .Collection(a => a.VideoMetas) .Query() .Include(vm => vm.Instances) .LoadAsync(); await context.Entry(activity) .Collection(a => a.ImageMetas) .Query() .Include(im => im.Instances) .LoadAsync(); await context.Entry(activity) .Reference(a => a.Procedure) .Query() .Include(p => p.Attributes) .LoadAsync(); return activity;

更多推荐

EF Core 3,优化大量Include/ThenInclude

本文发布于:2023-11-13 22:55:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1585547.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Core   EF   ThenInclude   Include

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!