【问题标题】:Change sql query to linq in mvc在mvc中将sql查询更改为linq
【发布时间】:2018-01-23 07:31:40
【问题描述】:

我想使用 join 语句将 sql 查询更改为 linq。查询应在将表 1 的记录与表匹配时检索列(daysstartdate)。简而言之,使用 join 语句将 sql 查询转换为 linq。

以下是我尝试过的。

SQL 查询(工作)

SELECT * 
FROM dbo."Batches" 
INNER JOIN dbo.StudentBatchRelation 
      on dbo.Batches.Id = dbo.StudentBatchRelation.BatchId 
WHERE 
      dbo.StudentBatchRelation.StudentId = '3d980306-e36e-4581-8c98-219717cb1668'

LINQ(不获取结果)

var result = (from t1 in contBatch.GetallBatchList()
              join t2 in contStudent.getAllStudentBatchList() 
                   on t1.Id equals t2.batchId where t2.studentId == studentid
              select new { t1.Days, t1.BatchDate }).ToList();

【问题讨论】:

  • 不带选择试试
  • 查询必须以 select 子句或 group 子句结尾
  • @user100020,尝试选择新的 {t1, t2} stackoverflow.com/questions/32433/…
  • 如果你看看我的问题,我也做过同样的事情
  • 你有没有出错?

标签: c# sql linq


【解决方案1】:

如果您的 EF 实体定义明确,您可以简化查询:

var result = Db.Batches
               .Include(p => p.StudentBatchRelation)
               .Where(p => p.StudentBatchRelation.StudentId = "3d980306-e36e-4581-8c98-219717cb1668")
               .ToList();

否则,如果您必须使用 Getallxxxx 函数,您可以这样做:

var result = (from t1 in contBatch.GetallBatchList()
              join t2 in contStudent.getAllStudentBatchList()
                     on t1.Id equals t2.batchId 
              where t2.studentId == "3d980306-e36e-4581-8c98-219717cb1668"
              select t1)
              .ToList();

【讨论】:

  • 您的回答与我在问题中提到的类似。
猜你喜欢
  • 2015-08-29
  • 1970-01-01
  • 2020-12-13
  • 1970-01-01
  • 1970-01-01
  • 2019-02-22
  • 1970-01-01
  • 1970-01-01
  • 2014-08-14
相关资源
最近更新 更多