Entity Framework 使用 .include 获取嵌套对象时抛出错误

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

我这里有一个查询,它获取单个实体对象和一个满足特定条件的嵌套实体,但我在执行它时收到错误消息。

这里是查询

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

这里是异常错误信息

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

我也用另一个 .First() 尝试了 运行,但仍然出现相同的错误消息

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

您无法过滤 Include 内的相关实体,您将需要使用预期结果投影您的查询​​或使用 explicit loading:

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(); 

如果你进行投影,它只会往返你的数据库一次,如果你使用显式加载,它将是两次。

仅供参考,如果您想投影结果,请投影到匿名类型或 DTO 上。更多信息 here