entityframeworkcoreislazy-loadedduringtheentitymodeltoDTOconvertingtheentityFrameworkCore(v2.0.1)遇到了一个问题。基本上,它是由该短语的任何其他版本加载的,当我不想要它时就懒惰了。这是一个简单的.NETCore控制台应用程序(使用Microsoft.EntityFrameworkCore.SqlServer(2.0.1)包)。使用Microsoft.EntityFrameworkCore;使用System.Collections.Generic;使用System.ComponentModel.DataAnnotations;使用System.ComponentModel.DataAnnotations.Schema;使用System.Linq;namespaceEfCoreIssue{classProgram{staticvoidMain(string[]args){vardbOptions=newDbContextOptionsBuilder().UseSqlServer("Server=.;Database=EfCoreIssue;Trusted_Connection=True;").Options;//如果数据库不存在,则创建和播种数据库。使用(vardbContext=newReportDbContext(dbOptions)){if(dbContext.Database.EnsureCreated()){stringalphas="ABCDEFGHIJKLMNOPQRSTUVWXYZ";foreach(charalphainalphas){varreport=newReport{Title=$"Report{alpha}"};对于(inttagId=0;tagIdnewReportDto{Id=r.Id,Title=r.Title,Tags=r.Tags.Select(rt=>rt.TagId)}).ToList();}}}classReportDbContext:DbContext{publicDbSetReports{get;放;}publicReportDbContext(DbContextOptionsoptions):base(options){}保护edoverridevoidOnModelCreating(ModelBuildermodelBuilder){modelBuilder.Entity().HasKey(rt=>new{rt.ReportId,rt.TagId});}}[Table("Report")]classReport{[Key]publicint}publicstringTitle{get;放;}publicvirtualICollectionTags{get;放;}publicReport(){Tags=newHashSet();}}[Table("ReportTag")]classReportTag}publicintTagId{get;放;}}classReportDto{publicintId{get;放;}公共字符串标题{得到;放;}公共IEnumerable标签{得到;放;现在,当执行ToList()方法检索数据时,它正在执行以下SQLSELECT[r].[Id],[r].[Title]FROM[Report]AS[r]正如你可以看,它没有努力加入[ReportTag]表,如果您实际上尝试读取ReportDto上Tags属性的值,那么它会触发另一个SQL查询SELECT[rt].[TagId]FROM[ReportTag]AS[rt]WHERE@_outer_Id=[rt].[ReportId]现在我知道EFCore不支持延迟加载,但这看起来非常像我在这个例子中的延迟加载,我不希望它延迟加载。我试过varreports=dbContext.Reportsasvarreports=dbContext.Reports.Include(r=>r.Tags)但它们没有效果。我什至尝试将Tags=r.Tags.Select(rt=>rt.TagId)更改为Tags=r.Tags.Select(rt=>rt.TagId).ToList()但这只会再次触发上面的辅助SQL查询26次。最后在绝望中我尝试了varreports=dbContext.Reportsasvarreports=dbContext.Reports.Include(r=>r.Tags).ThenInclude((ReportTagrt)=>rt.TagId)但可以理解地抛出异常ReportTag.TagId是不是导航属性。有没有人对我可以做什么有任何想法,以便它急切地加载到ReportDto.Tags属性中?正如您所注意到的,包含集合投影的EFCore投影查询当前存在两个问题-(1)它们导致每个集合执行N个查询,以及(2)它们延迟执行。问题(2)很奇怪,因为具有讽刺意味的是EFCore不支持相关实体数据的延迟加载,而这种行为有效地实现了它的投影。正如您已经发现的那样,至少您可以使用ToList()或类似的方法强制立即执行。问题(1)目前无法解决。它由Query:Optimizingqueriesprojectingrelatedcollectionssotheydon'tcauseN+1databasequeries#9282跟踪,根据路线图(减少n+1查询项)最终将在下一个EFcore2.1版本中修复(改进).我能想到的唯一解决方法是(具有更高的数据传输和内存使用成本)使用预先加载和事后投影(在LINQtoEntities的上下文中):时间是延迟加载共享的全部内容。如果对你有用,需要了解更多C#学习教程,希望大家多多关注——varreports=dbContext.Reports.Include(r=>r.Tags)//newReportDto{Id=r.Id,标题=r.Title,标签=r.Tags.Select(rt=>rt.TagId)}).ToList();本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
