使用case条件将SQL语句转换为LINQ

时间:2016-11-30 07:53:32

标签: c# sql-server linq

使用LINQ转换带有CASE语句的本机select语句时遇到问题。

这是在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语句

如何在case语句中用另一个sql实现sql语句?

1 个答案:

答案 0 :(得分: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通过填充所有属性来定义对象。