2013-06-04 48 views
0

我在Linq非常新手,不知道如何解决一些问题,即使在MS SQL查询中非常容易。如何将临时表与case语句SQL转换为Linq?

Select e.EmployeeID 
, e.EmployeeName 
, e.Division 
, e.DepartmentCode 
, e.DesignationGrpCode 
Into #temp 
from chr.dbo.EMPLOYEE e 
Where e.DepartmentCode in ( 
         Select DepartmentCode 
         from chr.dbo.EMPLOYEE 
         where EmployeeID = 'S-1287' 
         ) 

Select * from #temp t 
where t.EmployeeID in (
         Case When t.Division <> 'CHR' Then (Select EmployeeID from #temp where DesignationGrpCode = 'CorpDMGR') 
         Else (Select EmployeeID from #temp where DesignationGrpCode = 'MGT') End) 
Drop table #temp 

如何转换此查询到LINQ?请

这里是我的LINQ语句

var employee = new Common().Employee(); 

     var jobdesc = new Common().JobHistory(); 

     List<EMPLOYEE> dCode = (from e in employee 
           where e.EmployeeID == "S-1204" 
           select new EMPLOYEE 
           { 
            DepartmentCode = e.DepartmentCode 
           }).ToList(); 

     List<EMPLOYEE> emp = (from e in employee 
      join d in dCode on e.DepartmentCode equals d.DepartmentCode into temp 
      from t in temp.DefaultIfEmpty() 


      orderby e.EmployeeName 
      select new EMPLOYEE 
      { 
       EmployeeID = e.EmployeeID, 
       EmployeeName = e.EmployeeName 
      }).ToList(); 

但逼债知道如何检查CASE ELSE语句

+0

请添加您制作的LINQ,但没有做你以前的工作。 – Bazzz

+0

@Bazzz嗨,请检查,它已更新! – CMMaung

回答

1

给这一个去吧。它编译并运行在ideone,但是否则未经测试,所以祝你好运。

var temp = from e in context.EMPLOYEE 
      where (from f in context.EMPLOYEE 
        where f.EmployeeID == "S-1287" 
        && e.DepartmentCode == f.DepartmentCode 
        select f).Any() 
      select e; 

var result = from t in temp 
      where (from u in temp 
        where u.DesignationGrpCode 
          == (t.Division == "CHR" ? "CorpDMGR" : "MGT") 
        && t.EmployeeID == u.EmployeeID 
        select u).Any() 
      select t; 

假设你指向SQL Server 2005或以上,我希望LINQ是足够聪明,把临时表到一个WITH子句。

UPDATE:由于temp的子查询几乎肯定会返回一个值,你应该(假设雇员是主键),它分离出来:

string deptForS1287 = (from e in context.EMPLOYEE 
         where e.EmployeeID == "S-1287" 
         select DepartmentCode).Single(); 

var temp = from e in context.EMPLOYEE 
      where e.DepartmentCode == deptForS1287 
      select e; 

⋮ 

这有抛出异常的附带好处如果EMPLOYEE表没有提到员工S-1287。

+0

嗨兄弟,你的代码看起来像完美的工作,我用这个,没有错误,但没有数据出来。真混淆了一个!你有什么想法吗? – CMMaung

+1

@CMMaung:将其分解成更小的部分。首先检查'temp'是否有任何东西。如果是这样,请检查'result'的子查询是否有数据,等等。如果不是,那么检查'temp'的子查询是否返回任何东西。 –

+1

@CMMaung:我刚刚在原始查询中意识到错字。在'EmployeeID'上匹配'temp'的子查询应该在'DepartmentCode'上匹配。我修复它并添加了一个可能的改进。 –

1

在极端情况下,你可以做到这一点:

using (var context = new ConnectDb())  
    { 
     context.ExecuteStoreCommand("your query"); 
     // for exaple: context.ExecuteStoreCommand("TRUNCATE TABLE Peoples"); 
     context.SaveChanges(); 
    } 
+0

答案中没有LINQ。这不是OP正在寻找的东西。 – Steven

+0

@ Rim4irok感谢您的信息。看起来像解决方案之一:D – CMMaung