简体   繁体   English

使用.include提取嵌套对象时,实体框架抛出错误

[英]Entity Framework throwing error when fetching a nested object using .include

I have a query here that fetches a single entity object and only one nested entity that meets a specific condition, but I'm receiving an error when executing it. 我在这里有一个查询,该查询只获取一个实体对象,而只有一个满足特定条件的嵌套实体,但是执行该对象时会收到错误消息。

Here is the query 这是查询

Profile profile = dbContext.Profiles.Where(i => i.ApplicationUserGuid == guiId)
               .Include(i => i.ProfileImages.Where(k => k.IsMainImage == true)).First();

And here is the exception error message 这是异常错误消息

The Include path expression must refer to a navigation property defined on the type. 包含路径表达式必须引用在类型上定义的导航属性。 Use dotted paths for reference navigation properties and the Select operator for collection navigation properties. 使用虚线路径作为参考导航属性,使用“选择”运算符作为集合导航属性。 Parameter name: path 参数名称:路径

I also tried running it with another .First(), but still same error message 我也尝试使用另一个.First()运行它,但仍然出现相同的错误消息

Profile profile = dbContext.Profiles.Where(i => i.ApplicationUserGuid == guiId)
              .Include(i => i.ProfileImages.Where(k => k.IsMainImage == true).First()).First();

You can't filter related entities inside an Include , you are going to need to project your query with the expected result or use explicit loading : 您不能在Include内过滤相关实体,您将需要使用预期结果来投影查询或使用显式加载

Profile profile = dbContext.Profiles
                           .Where(i => i.ApplicationUserGuid == guiId)
                           .First();
dbContext.Entry(profile) //Explicit Loading
         .Collection(b => b.ProfileImages) 
         .Query() 
         .Where(k => k.IsMainImage == true).Take(1)
         .Load(); 

If you do the projection it will be only one round trip to your database, and if you use explicit loading it will be two. 如果进行投影,则仅是数据库的一次往返;如果使用显式加载,则将是两次。

Just a FYI, in case you think to project the result, project to an anonymous type or onto a DTO. 仅供参考,以防万一,您打算将结果投影到匿名类型或DTO上。 More info here . 更多信息在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM