为什么Linq-to-SQL会添加不必要的COUNT()?

时间:2017-08-15 03:08:48

标签: sql-server linq linq-to-sql

以下是我的表格:

create table customer 
(
    cid int primary key,
    name varchar(32)
)

create table ord 
(
    oid int primary key,
    cid int foreign key references customer,
    address varchar(20)
)

这是我的Linq-to-SQL语句:

var aaa = from c in db.Customer
          select new { c, o = c.Ord.ToList() };

这是Linq-to-SQL生成的无法解释的查询:

SELECT 
    [t0].[cid] AS [Cid], [t0].[name] AS [Name], [t1].[oid] AS [Oid], 
    [t1].[cid] AS [Cid2], [t1].[address] AS [Address], 
    (SELECT COUNT(*)
     FROM [dbo].[ord] AS [t2]
     WHERE [t2].[cid] = [t0].[cid]) AS [value]
FROM [dbo].[customer] AS [t0]
LEFT OUTER JOIN [dbo].[ord] AS [t1] ON [t1].[cid] = [t0].[cid]
ORDER BY [t0].[cid], [t1].[oid]

我想了解如何摆脱COUNT(*)部分。这完全是不必要的!

1 个答案:

答案 0 :(得分:1)

LINQ需要COUNT(*)才能确定将为o = c.Ord.ToList()返回的条目数。