我正在将bltoolkit用作ORM映射器。
我的问题是,它生成了错误的SQL。
我有此查询:
var qry = from i in s.Query<ChannelDTO>()
join o in s.Query<StorageShelfDTO>() on i.Id equals o.ChannelID into p1
select new {i.Id, n = p1.Count()};
var qry2 = qry;
qry2 = qry2.Where(x => x.n == 0);
Debug.Print("Entrys: " + qry2.ToList().ToString());
生成此SQL:
SELECT
[x].[Id] as [Id1]
FROM
(
SELECT
(
SELECT
Count(*)
FROM
[WMS_StorageShelf] [t1]
WHERE
[i].[ID] = [t1].[ChannelID]
) as [c1],
[i].[ID] as [Id]
FROM
[WMS_Channel] [i]
) [x]
WHERE
[x].[c1] = 0
缺少外部选择中的计数字段!
但是,当我删除条件时:
qry2 = qry2.Where(x => x.n == 0);
然后生成正确的SQL。
生成的查询是正确的。
您的初始linq语句:
var qry = from i in s.Query<ChannelDTO>()
join o in s.Query<StorageShelfDTO>() on i.Id equals o.ChannelID into p1
select new {i.Id, n = p1.Count()};
将生成类似于:
的SQLSELECT
(
SELECT
Count(*)
FROM
[WMS_StorageShelf] [t1]
WHERE
[i].[ID] = [t1].[ChannelID]
) as [c1],
[i].[ID] as [Id]
FROM
[WMS_Channel] [i]
现在,当您将第二部分添加到查询(QRY2)时,这将添加到您的原始查询中,因为它使用了延期执行。因此,执行时,最终查询看起来像这样:
var finalQuery = (from i in s.Query<ChannelDTO>()
join o in s.Query<StorageShelfDTO>() on i.Id equals o.ChannelID into p1
select new {i.Id, n = p1.Count()}).Where(x => x.n == 0)
这就是为什么您以SQL生成的方式生成的原因。
如果您不需要延期执行并实际需要两个不同的查询,则在第一个查询上调用.ToList()
迫使立即执行,您将看到您期望的查询。
这样:
var qry = (from i in s.Query<ChannelDTO>()
join o in s.Query<StorageShelfDTO>() on i.Id equals o.ChannelID into p1
select new {i.Id, n = p1.Count()}).ToList();