如何在Entity Framework中显式加载相关实体?

时间:2016-06-18 02:18:16

标签: c# .net entity-framework entity-framework-6

我和EF有一个奇怪的问题,我希望你可以帮助我。

我已经从数据库(Campaign)加载了一个对象,现在我想循环遍历一个具有一对多关系的相关实体。

最初,当代码循环遍历集合(ListingImages)时,它为每个图像触发了一个选择语句,这显然不是理想的。

我设法使用以下方法显式加载所有列表图片..

dbContext.Entry(campaign.Model.ListingVersion.Listing)
.Collection(x => x.ListingImages)
.Query()
.Include(x => x.Image)
.Load();

然后循环浏览列表图片......

foreach (var listingImage in campaign.Model.ListingVersion.Listing.ListingImages) 
{
    _log.Info(listingImage.Image.InsertedDate); 
}

这会导致一个单独的查询进入数据库并返回多个记录(正如预期的那样)但是当我遍历我的foreach中的集合时,它也会触发相同(略微修改)的查询两次进入数据库。唯一的区别是第二个查询没有Image表的内连接。

这是从.Load()...

中发出的SQL
SELECT [Extent1].[ImageTypeId]   AS [ImageTypeId],
   [Extent1].[Id]            AS [Id],
   [Extent1].[ListingId]     AS [ListingId],
   [Extent1].[ImageId]       AS [ImageId],
   [Extent1].[CapturedDate]  AS [CapturedDate],
   [Extent2].[Id]            AS [Id1],
   [Extent2].[URLHash]       AS [URLHash],
   [Extent2].[Url]           AS [Url],
   [Extent2].[Format]        AS [Format],
   [Extent2].[InsertedDate]  AS [InsertedDate],
   [Extent2].[RequestErrors] AS [RequestErrors],
   [Extent2].[S3Uploaded]    AS [S3Uploaded],
   [Extent2].[QueuePriority] AS [QueuePriority],
   [Extent2].[HasThumbnail]  AS [HasThumbnail]
FROM   [dbo].[ListingImage] AS [Extent1]
INNER JOIN [dbo].[Image] AS [Extent2] ON [Extent1].[ImageId] = [Extent2].[Id]
WHERE  [Extent1].[ListingId] = 'b3c18c0c-4401-e511-945a-06045dea07cc'

这是从foreach声明中得到的SQL ......

SELECT [Extent1].[Id]           AS [Id],
       [Extent1].[ListingId]    AS [ListingId],
       [Extent1].[ImageId]      AS [ImageId],
       [Extent1].[CapturedDate] AS [CapturedDate],
       [Extent1].[ImageTypeId]  AS [ImageTypeId]
FROM   [dbo].[ListingImage] AS [Extent1]
WHERE  [Extent1].[ListingId] = 'b3c18c0c-4401-e511-945a-06045dea07cc'

第一个查询应该为EF提供从ListingImages获取数据所需的一切,而不必返回数据库......任何想法如何防止第二个查询被解雇?

0 个答案:

没有答案
相关问题