SQL Server Profiler不会跟踪所有Entity Framework 4查询 - 问题

时间:2011-12-12 21:44:19

标签: .net linq sql-server-2008 entity-framework

我正在阅读Programming Entity Framework, 2nd Edition,在第一章中有一个非常简单的查询:

    private static void QueryContacts()
    {
        using (var context = new SampleEntities())
        {
            var contacts = context.Contacts.Where(c => c.FirstName == "Robert");
            var res = (contacts as ObjectQuery<Contact>).Execute(MergeOption.NoTracking);

            foreach (var contact in res)
            {
                foreach (var address in contact.Addresses)
                {
                    Console.WriteLine("\t{0}", address.City);
                }
            }
        }
        Console.Write("Press Enter...");
        Console.ReadLine();
    }

当我将SQL分析器附加到数据库实例时,我可以看到执行了以下SQL:

SELECT 
[Extent1].[ContactID] AS [ContactID], 
[Extent1].[FirstName] AS [FirstName], 
[Extent1].[LastName] AS [LastName], 
[Extent1].[Title] AS [Title], 
[Extent1].[AddDate] AS [AddDate], 
[Extent1].[ModifiedDate] AS [ModifiedDate]
FROM [dbo].[Contact] AS [Extent1]
WHERE N'Robert' = [Extent1].[FirstName]

但是没有查询地址表的迹象(即使有地址)。

当我附加Entity Framework Profiler时,我可以看到两者:

SELECT [Extent1].[ContactID]    AS [ContactID],
       [Extent1].[FirstName]    AS [FirstName],
       [Extent1].[LastName]     AS [LastName],
       [Extent1].[Title]        AS [Title],
       [Extent1].[AddDate]      AS [AddDate],
       [Extent1].[ModifiedDate] AS [ModifiedDate]
FROM   [dbo].[Contact] AS [Extent1]
WHERE  N'Robert' = [Extent1].[FirstName]

SELECT [Extent1].[addressID]     AS [addressID],
       [Extent1].[Street1]       AS [Street1],
       [Extent1].[Street2]       AS [Street2],
       [Extent1].[City]          AS [City],
       [Extent1].[StateProvince] AS [StateProvince],
       [Extent1].[CountryRegion] AS [CountryRegion],
       [Extent1].[PostalCode]    AS [PostalCode],
       [Extent1].[AddressType]   AS [AddressType],
       [Extent1].[ContactID]     AS [ContactID],
       [Extent1].[ModifiedDate]  AS [ModifiedDate]
FROM   [dbo].[Address] AS [Extent1]
WHERE  [Extent1].[ContactID] = 209 /* @EntityKeyValue1 */

您是否知道SQL Server Profiler发生了什么,以便不会捕获对Address表的查询?

由于

2 个答案:

答案 0 :(得分:8)

宾果!

我选择了所有事件类型,结果发现地址查询可以作为RPC:已完成,而联系人可以作为SQL进行跟踪:BatchCompleted:

exec sp_executesql N'SELECT 
[Extent1].[addressID] AS [addressID], 
[Extent1].[Street1] AS [Street1], 
[Extent1].[Street2] AS [Street2], 
[Extent1].[City] AS [City], 
[Extent1].[StateProvince] AS [StateProvince], 
[Extent1].[CountryRegion] AS [CountryRegion], 
[Extent1].[PostalCode] AS [PostalCode], 
[Extent1].[AddressType] AS [AddressType], 
[Extent1].[ContactID] AS [ContactID], 
[Extent1].[ModifiedDate] AS [ModifiedDate]
FROM [dbo].[Address] AS [Extent1]
WHERE [Extent1].[ContactID] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=220

答案 1 :(得分:0)

在循环内部延迟加载期间查询地址。使用Contacts进行单次拍摄会更有效。为此,您需要:

var res = (contacts as ObjectQuery<Contact>).Include("Addresses").Execute(MergeOption.NoTracking);