我正在阅读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表的查询?
由于
答案 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);