简体   繁体   English

为什么此Linq查询从同一SQL视图返回3个相同的行?

[英]Why is this Linq Query returning 3 identical rows from the same SQL view?

I have a simple view defined MSSQL 2008. The view is defined as follows: 我有一个定义MSSQL 2008的简单视图。该视图定义如下:

    SELECT     dbo.tblCompany.CompanyID, dbo.tblAccount.Carrier, SUM(ISNULL(dbo.tblLine.LineCharge, 0)) + SUM(ISNULL(dbo.tblLine.FeatureCharge, 0)) 
                      + SUM(ISNULL(dbo.tblLine.AccessCharge, 0)) AS SumOfCharges
FROM         dbo.tblCompany LEFT OUTER JOIN
                      dbo.tblCompany_Location LEFT OUTER JOIN
                      dbo.tblAccount LEFT OUTER JOIN
                      dbo.tblLine LEFT OUTER JOIN
                      dbo.tblBill_Data ON dbo.tblLine.LineID = dbo.tblBill_Data.LineID ON dbo.tblAccount.AccountID = dbo.tblLine.AccountID ON 
                      dbo.tblCompany_Location.LocationID = dbo.tblAccount.LocationID ON dbo.tblCompany.CompanyID = dbo.tblCompany_Location.CompanyID
GROUP BY dbo.tblCompany.CompanyID, dbo.tblAccount.Carrier

Which returns data in the form of: 它以以下形式返回数据:

1    Carrier1          $70.00
1    Carrier2         $100.00
1    Carrier3         $150.00
3    Carrier2          $60.00
....etc

This works fine with an SQL select statement. 使用SQL select语句可以很好地工作。

I have a VB linq query that just sets a where clause based on the CompanyID. 我有一个VB linq查询,它只是根据CompanyID设置where子句。

Dim expenses = From exp In Me.vw_CarrierExpenses _
                       Where exp.CompanyID = companyId _
                       Select exp

        Return expenses.ToList()

If I filter based on a CompanyID of 1, using the example data above, I get the first row 3 times: 如果我使用上面的示例数据基于1的CompanyID进行过滤,我将获得3次第一行:

1    Carrier1          $70.00
1    Carrier1          $70.00
1    Carrier1          $70.00

I must be missing something very simple here. 我一定在这里遗漏了一些非常简单的东西。 It always returns the correct amount of rows but the data is always identical. 它始终返回正确的行数,但数据始终相同。 Thanks. 谢谢。

I keep forgetting that LINQ needs to have a true unique primary key field in query model. 我一直忘了LINQ在查询模型中需要有一个真正唯一的主键字段。 I added the following 'fake' primary key to my view by adding: 我通过添加以下“假”主键到视图中:

 ROW_NUMBER() OVER (ORDER BY dbo.tblCompany.CompanyID) As 'CarrierExpenseID'

to my view fields and then adding this as my primary key in my view model. 到我的视图字段,然后将其添加为我的视图模型的主键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM