将Sql转换为Linq

时间:2009-12-11 12:28:06

标签: c# linq

如何翻译

select *from
   (
     select EmployeeID,FirstName,LastName,Region from Employees where city
     in ('London','Seattle') 
   )
   x
where x.Region is not null

进入Linq Equivalent。

我尝试过(但也会选择空值)

LinqDBDataContext Context = new LinqDBDataContext();

   var query = from emps in

                  (
                       from empls in Context.Employees
                       where empls.City == "London" || empls.City == "Seattle"
                        && empls.Region != null
                             select new
                              {
                                 FirstName = empls.FirstName,
                                 LastName = empls.LastName,
                                 City = empls.City,
                                 Region = empls.Region
                              }
                   )
              select emps;


            GridView1.DataSource = query;
            GridView1.DataBind();

4 个答案:

答案 0 :(得分:2)

Threadpool,您需要查看一个名为Linqer的产品(我与之无关)。太棒了。它将SQL查询转换为LINQ。我还没有遇到它无法处理的查询。

答案 1 :(得分:2)

这是你的括号。你在城市的OR声明中错过了它们。

LinqDBDataContext Context = new LinqDBDataContext();

   var query = from emps in

                  (
                       from empls in Context.Employees
                       where (empls.City == "London" || empls.City == "Seattle")
                        && empls.Region != null
                             select new
                              {
                                 FirstName = empls.FirstName,
                                 LastName = empls.LastName,
                                 City = empls.City,
                                 Region = empls.Region
                              }
                   )
              select emps;


            GridView1.DataSource = query;
            GridView1.DataBind();

答案 2 :(得分:2)

您需要将where子句更改为:

其中(empls.City ==“伦敦”|| empls.City ==“西雅图”)&& empls.Region!= null

如果没有parens,你将获得伦敦的空值

答案 3 :(得分:1)

你的sql可以被命名为:

select EmployeeID,FirstName,LastName,Region 
from Employees 
where city in ('London','Seattle') 
and Region is not null