2016-11-30 48 views
-2

我在使用LINQ转换CASE语句的本机select语句时遇到问题。将SQL语句转换为具有case条件的LINQ

这是在SQL Server中工作的本地SQL:

select 
    v.vehl_ContainerNo as cont_name, v.vehl_Name, 
    v.vehl_drivername, v.vehl_entrancedate, v.vehl_customsdec, 
    c.Capt_AR as VehicleState, 
    case 
     when v.vehl_rampid is null 
      then '' 
      else (select ramp_Name 
       from Ramp 
       where ramp_RampID = v.vehl_rampid) 
    end as cont_rampid 
from 
    Vehicle v, Custom_Captions c 
where 
    v.vehl_state = c.Capt_Code 
    and c.Capt_Family = 'vehl_state' 
    and v.vehl_ClearanceCompany = 471 

我想要得到的ramp_name:

  • 如果vehl_rampid为null,则返回一个空字符串

  • 否则会执行另一个select语句以从rampl表中得到ramp_name,其中vehl_rampid等于ramp_rampid。

当我用下面的LINQ声明:

//List<qryRslt> query = (from v in db.Vehicles 
        //      join cus in db.Custom_Captions on v.vehl_state equals cus.Capt_Code 
        //      join ram in db.Ramps on v.vehl_rampid equals ram.ramp_RampID 
        //      where 
        //      cus.Capt_Family == "vehl_state" && v.vehl_Deleted == null && v.vehl_ClearanceCompany == p.pusr_CompanyId 
        //      select new qryRslt 
        //      { 
        //       vehl_ContainerNo = v.vehl_ContainerNo, 
        //       vehl_Name = v.vehl_Name, 
        //       vehl_drivername=v.vehl_drivername, 
        //       vehl_entrancedate=v.vehl_entrancedate, 
        //       vehl_customsdec=v.vehl_customsdec, 
        //       VehicleState=v.vehl_state, 
        //       cont_rampid=v.vehl_rampid==null?" ":ram.ramp_Name 


        //      }).ToList(); 

它给了我一个意外的结果,从写在SQL Server本机SQL语句的不同

我怎样才能实现与另一个SQL语句sql在case语句中?

+0

请添加您尝试的LINQ代码。 –

回答

0

这取决于你回来。让我们假设你正在试图返回类:MyClass

然后LINQ会看起来像:

List<MyClass> result = (from c in Vehicle 
      from x in Custom_Captions 
      join z in Ramp on c.vehl_rampId equals z.ramp_RampID 
      where c.vehl_state == x.Capt_Code 
        && x.Capt_Family == 'vehl_state' 
        && c.vehl_ClearanceCompany == 471 
      select new MyClass{ 
        prop1 = c.vehl_rampid is null ? "" : z.ramp_Name 
      }).ToList(); 

上面的代码使用Object Initialiser填充它的所有属性来定义对象。

+0

如果你想添加另一个'from ... where ... select'而不是'c.vehl_rampid',这很可能会变成OP需要的答案。 –

+0

我试图做到这一点,但它给了我不同的输出与sql服务器,当我试图加入'v.vehl_rampid等于ram.ramp_RampID'坡道表,并且当选择以下内容: 'cont_rampid = v.vehl_rampid == null?“”:ram.ramp_Name' 我认为问题是当我加入车辆坡道 –

+0

感谢您更新您的答案,但结果不同于在sql服务器的结果我怎么做select语句在另一个sql语句?? –