我有一个简单的联接查询,连接两个表(一个类别有很多产品:]
using (ProdContext db = new ProdContext())
{
var query = from category in db.Categories
join product in db.Products
on category.CategoryID equals product.CategoryID into productList
select new
{
categoryName = category.Name,
products = productList
};
foreach (var c in query)
{
Console.WriteLine("* {0}", c.categoryName);
foreach (var p in c.products)
{
Console.WriteLine(" - {0}", p.Name);
}
};
}
对于班级:
class Category
{
public int CategoryID { get; set; }
public String Name { get; set; }
public List<Product> Products { get; set; }
}
class Product
{
public int ProductID { get; set; }
public String Name { get; set; }
public int UnitsInStock { get; set; }
public int CategoryID { get; set; }
}
class ProdContext : DbContext
{
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }
}
并且通常一切正常,但是当我开始尝试快速加载和延迟加载时,我感到困惑,因为无论我在查询末尾添加.ToList()
还是我的SQL请求总是看起来像这样:
SELECT
[Project1].[CategoryID] AS [CategoryID],
[Project1].[Name] AS [Name],
[Project1].[C1] AS [C1],
[Project1].[ProductID] AS [ProductID],
[Project1].[Name1] AS [Name1],
[Project1].[UnitsInStock] AS [UnitsInStock],
[Project1].[CategoryID1] AS [CategoryID1],
FROM
(SELECT
[Extent1].[CategoryID] AS [CategoryID],
[Extent1].[Name] AS [Name],
[Extent2].[ProductID] AS [ProductID],
[Extent2].[Name] AS [Name1],
[Extent2].[UnitsInStock] AS [UnitsInStock],
[Extent2].[CategoryID] AS [CategoryID1],
CASE WHEN ([Extent2].[ProductID] IS NULL)
THEN CAST(NULL AS int) ELSE 1 END AS [C1]
FROM
[dbo].[Categories] AS [Extent1]
LEFT OUTER JOIN
[dbo].[Products] AS [Extent2] ON [Extent1].[CategoryID] = [Extent2].[CategoryID]) AS [Project1]
ORDER BY
[Project1].[CategoryID] ASC, [Project1].[C1] ASC
并且据我所知,当我使用.ToList()
(紧急加载)时,它应该看起来像这样,但是当我使用(默认)延迟加载时,它应该发送许多sql请求,分别询问foreach循环的所有元素。我的问题是-为什么没有区别,并且总是只发送一个SQL?
...当我使用
.ToList()
时(急切加载)...当我使用(默认)延迟加载时