BLToolKit生成错误的SQL

时间:2014-03-12 21:58:26

标签: c# sql linq bltoolkit

我使用BLToolKit作为ORM Mapper。

我现在的问题是,它会生成错误的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是Gnerated

1 个答案:

答案 0 :(得分:0)

生成的查询是正确的。

您有初始的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()};

这将生成类似于:

的SQL
SELECT
    (
        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();