【问题标题】:Why don't my SQL results match my Linq results?为什么我的 SQL 结果与我的 Linq 结果不匹配?
【发布时间】:2015-08-27 17:05:01
【问题描述】:

当我在 SQL 中运行这个查询时,我得到了我想要的:

SELECT Auckland_Park.Formative.[Formative Name]
FROM Auckland_Park.LearningUnit 
INNER JOIN Auckland_Park.Formative 
ON Auckland_Park.LearningUnit.ID = Auckland_Park.Formative.FK_LU 
INNER JOIN Auckland_Park.Reference 
INNER JOIN Auckland_Park.Course 
ON Auckland_Park.Reference.FK_Course = Auckland_Park.Course.ID 
ON Auckland_Park.LearningUnit.ID = Auckland_Park.Reference.FK_LU
WHERE Auckland_Park.Course.Name = 'BI'

我的结果:

Querying SQL Build 
Report Develop 
Java App Develop 
Andriod App Set up
SharePoint Server

但是当我使用我的 C# 应用程序时,我使用的是 LINQ to SQL,我的 LINQ 查询如下所示:

//LINQ Query to fill Foramtive Name ComboBox
CTUDataContext data = new CTUDataContext();
var course = (from r in data.LearningUnits                      
              join a in data.Formatives
              on r.ID equals a.FK_LU
              join f in data.References
              on r.ID equals f.FK_LU
              join g in data.Courses 
              on f.FK_LU equals g.ID
              where g.Name == ("BI")
              select new
              {
                  formativeName = a.Formative_Name,
                  ID = a.ID

              } 
              ).ToList();
txtFormativeName.ItemsSource = course;
txtFormativeName.DisplayMemberPath = "formativeName";
txtFormativeName.SelectedValuePath = "ID";

看起来一样,但我得到的结果与上面的 SQL 查询不同。

【问题讨论】:

  • Linq 查询结果如何?
  • 结果来自同一张表,但不在我的 WHERE 子句“BI”下..
  • 您查看过您的 LINQ 查询生成的 SQL 吗?
  • “但不在我的 where 子句下”是什么意思?你需要很多更清楚你所期望的和你实际看到的。
  • WHERE 给了我上面 SQl 查询的结果。但在 LINQ 中我没有得到那个结果。我得到的结果来自同一个表,但不是我想要的行.

标签: c# sql linq linq-to-sql


【解决方案1】:
    //LINQ Query to fill Foramtive Name ComboBox
CTUDataContext data = new CTUDataContext();
var course = (from r in data.LearningUnits                      
              join a in data.Formatives
              on r.ID equals a.FK_LU
              join f in data.References
              on r.ID equals f.FK_LU
              join g in data.Courses 
              on f.FK_LU equals g.ID
              where g.Name == ("BI")
              select new
              {
                  formativeName = a.Formative_Name,
                  ID = a.ID

              } 
              ).ToList();
txtFormativeName.ItemsSource = course;
txtFormativeName.DisplayMemberPath = "formativeName";
txtFormativeName.SelectedValuePath = "ID";

回答:

on f.FK_LU equals g.ID


f.FK_LU

必须替换为

f.FK_Course

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-25
    • 2016-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多