第一次SQL到Linq的转换

本文关键字:转换 Linq SQL 第一次 | 更新日期: 2023-09-27 18:20:16

我是LINQ的新手,有人能指导我如何在LINQ中转换以下SQL查询吗。

Select tblIns.InsID, tblProg.ProgName 
from tblIns, tblProg 
Where tblIns.InsID = tblProg.InsID

我正在从事MVC2项目,我有dataContext和reposetores,请在下面的代码中找到我需要的查询:

public IQueryable<tblInstitute> InsRepeater()
{
    return from Inst in _db.tblInstitutes 
           from Progs in _db.tblPrograms 
           Where Inst.InstituteID = Progs.InstituteID 
           Select Inst.InstituteID, Progs.ProgramName
 }

第一次SQL到Linq的转换

首先需要的是一个模拟数据库的数据上下文。下面是一个如何使用linq-to-sql执行此操作的示例。您也可以使用实体框架(EF)或任何其他提供商来完成此操作。

一旦创建了表,查询就会直接转换:

var results = from insEntity in tablIns
              from progEntity in tablProg
              where insEntity.InsID equals progEntity.InsID
              select new { insEntity.InsID, progEntity.ProgName };

对于你提出的问题,我认为这是非常有用的。在未来,最好写一些问题来解释你试图做什么,你尝试了什么,然后你被困在哪里。这个问题应该足够具体,让你度过下一个难关。


根据您的编辑:您的查询需要有小写的whereselect,并且需要以分号结束语句(假设它是c#)。然后您选择语句需要选择一个新对象。结果看起来像这样:

public IQueryable<tblInstitute> InsRepeater()
{
    return from Inst in _db.tblInstitutes 
           from Progs in _db.tblPrograms 
           where Inst.InstituteID equals Progs.InstituteID 
           select Inst; // for the current method header
           //select new { Inst.InstituteID, Progs.ProgramName }; // to use this one you'll have to create a new type with the properties you want to return
}

首先需要1.创建实体类。2.数据上下文。3.定义关系4.查询

参考

from I in tblIns
from P in tblProg 
Where I.InsID = P.InsID
Select I.InsID, P.ProgName 

假设您在数据库中正确设置了外键,您就可以这样做,而不需要自己连接:

from x in db.tblProgs
select x.tblIns.id, x.Progname