Linq to Entities SQL生成问题

时间:2011-06-28 12:23:34

标签: vb.net tsql entity-framework-4 linq-to-entities

我有一个VB.Net Linq to Entities查询,它从SQL Server 2005返回数据。如果我将查询复制到LinqPad,它按预期工作,但当我尝试运行代码时,它返回所有等于1的计数。

唯一改变的是日期值在LinqPad中被记录并作为VB中的参数传递。

任何想法有什么不对?

ViewModel的日期参数如下所示,应代表2011年1月1日 - > 2011年2月1日

?的startDate “#1/1 /网友排名” ?结束日期 “#2 /二千○十一分之一#”

Public Function GetPLMNewPartCounts(ByVal startDate As Date, ByVal endDate As Date) As IEnumerable(Of NewPartsCounts)

        Return From i In ObjectContext.tblEngineeringDashboard_ItemList
                    Join t In ObjectContext.tblTimes On t.ID Equals i.TimeID
                    Join b In ObjectContext.tblEngineeringDashboard_Business On b.ID Equals i.BusinessID
                    Where t.Period >= startDate And t.Period <= endDate
                    Group b By Key = b.BusinessUnit Into Group
                    Select New NewPartsCounts With {.BusinessUnit = Key,
                                                    .NewPartsCount = Group.Select(Function(c) c.BusinessUnit).Distinct().Count()}

End Function

SQL profiler中的TSQL

exec sp_executesql N'SELECT 
1 AS [C1], 
[Project4].[BusinessUnit] AS [BusinessUnit], 
[Project4].[C1] AS [C2]
FROM ( SELECT 
    [Project2].[BusinessUnit] AS [BusinessUnit], 
    (SELECT 
        COUNT(1) AS [A1]
        FROM ( SELECT DISTINCT 
            [Extent6].[BusinessUnit] AS [BusinessUnit]
            FROM   [dbo].[tblEngineeringDashboard_ItemList] AS [Extent4]
            INNER JOIN [dbo].[tblTime] AS [Extent5] ON [Extent4].[TimeID] = [Extent5].[ID]
            INNER JOIN [dbo].[tblEngineeringDashboard_Business] AS [Extent6] ON [Extent4].[BusinessID] = [Extent6].[ID]
            WHERE ([Extent5].[Period] >= @p__linq__0) AND ([Extent5].[Period] <= @p__linq__1) AND ([Project2].[BusinessUnit] = [Extent6].[BusinessUnit])
        )  AS [Distinct2]) AS [C1]
    FROM ( SELECT 
        [Distinct1].[BusinessUnit] AS [BusinessUnit]
        FROM ( SELECT DISTINCT 
            [Extent3].[BusinessUnit] AS [BusinessUnit]
            FROM   [dbo].[tblEngineeringDashboard_ItemList] AS [Extent1]
            INNER JOIN [dbo].[tblTime] AS [Extent2] ON [Extent1].[TimeID] = [Extent2].[ID]
            INNER JOIN [dbo].[tblEngineeringDashboard_Business] AS [Extent3] ON [Extent1].[BusinessID] = [Extent3].[ID]
            WHERE ([Extent2].[Period] >= @p__linq__0) AND ([Extent2].[Period] <= @p__linq__1)
        )  AS [Distinct1]
    )  AS [Project2]
)  AS [Project4]',N'@p__linq__0 datetime,@p__linq__1 datetime',@p__linq__0='2011-01-01 00:00:00:000',@p__linq__1='2011-02-01 00:00:00:000'

1 个答案:

答案 0 :(得分:0)

我的错。忘了删除.Distinct。 DOH!