Linq-To-SQL多次访问数据库

时间:2012-08-08 17:09:50

标签: c# sql-server linq-to-sql sqlprofiler

我试图通过在数据库的一次行程中包含子属性来提高我的Linq-to-SQL查询效率。我开始尝试各种linq查询来实现这一目标。查询变得越来越复杂,所以我尝试了LoadWith()选项:

我的DAL类的构造函数设置LoadWith()设置:

public TrackerJobData()
{
    dataLoadOptions = new DataLoadOptions();

    dataLoadOptions.LoadWith<TrackerJobRecord>(x => x.SpecBarcodeRecords);
    dataLoadOptions.LoadWith<TrackerJobRecord>(x => x.TrackerJobEquipmentTriggerRecords);
    dataLoadOptions.LoadWith<TrackerJobRecord>(x => x.EtaRecord);

    this.Database.LoadOptions = dataLoadOptions;
}

这是我正在使用的查询:

public TrackerJob GetItem(int trackerJobId)
{
    TrackerJobRecord record =
        (from trackerJob in this.Database.TrackerJobRecords
         where trackerJob.TrackerJobId == trackerJobId
         select trackerJob).FirstOrDefault();

    return record.Map();
}

当我在linq查询上调试和F10 (而不是返回)时,我在SQL事件探查器中得到了这个输出:

enter image description here

请原谅我对SQL事件探查器的无知,但这三条突出显示的行是否意味着从客户端(我的代码)到服务器有三次往返旅行?如果是这样,为什么? SQL Server是否会在一次行程中执行多个sp_executesql调用?

因为我认为LoadWith()会消除多个调用,我做错了什么?

修改

以下是SQL事件探查器中的三个语句:

exec sp_executesql N'SELECT TOP (1) [t0].[TrackerJobId], [t0].[Name], [t0].[EtaId], [t0].[SamplingProcessorTypeId], [t0].[Description], [t0].[LastModifiedUser], [t0].[LastModifiedTime], [t0].[VersionNumber], [t0].[Active], [t0].[Archived], [t1].[EtaId] AS [EtaId2], [t1].[EtaNumber], [t1].[Title], [t1].[State], [t1].[DateInitialized], [t1].[EtaOriginatorId], [t1].[Quantity], [t1].[Ehs], [t1].[Ship], [t1].[InternalUse], [t1].[DateClosed], [t1].[ExperimentId], [t1].[Disposition], [t1].[TestType], [t1].[LastModifiedUser] AS [LastModifiedUser2], [t1].[LastModifiedTime] AS [LastModifiedTime2], [t1].[VersionNumber] AS [VersionNumber2]
FROM [AutoTracker].[TrackerJob] AS [t0]
INNER JOIN [Global].[Eta] AS [t1] ON [t1].[EtaId] = [t0].[EtaId]
WHERE [t0].[TrackerJobId] = @p0',N'@p0 int',@p0=17

exec sp_executesql N'SELECT [t0].[SpecBarcodeId], [t0].[TrackerJobId], [t0].[EquipmentId], [t0].[StartTime], [t0].[EndTime], [t0].[LastModifiedUser], [t0].[LastModifiedTime], [t0].[VersionNumber]
FROM [AutoTracker].[SpecBarcode] AS [t0]
WHERE [t0].[TrackerJobId] = @x1',N'@x1 int',@x1=17

exec sp_executesql N'SELECT [t0].[TrackerJobId], [t0].[EquipmentId], [t0].[LastModifiedUser], [t0].[LastModifiedTime], [t0].[VersionNumber]
FROM [AutoTracker].[TrackerJobEquipmentTrigger] AS [t0]
WHERE [t0].[TrackerJobId] = @x1',N'@x1 int',@x1=17

2 个答案:

答案 0 :(得分:2)

答案 1 :(得分:1)

每个SQL事件探查器调用都代表从客户端到数据库服务器实例的单个往返。 SQL Server支持在单个往返中返回数据集,但我不确定如何使用LINQ to SQL执行此操作。