将C#Linq转换为T-Sql

时间:2017-05-04 08:53:31

标签: c# sql linq linq-to-sql

我是初级开发人员并尝试将以下linq语句转换为T-Sql:

    var results = context
      .Employees
      .Where(item => (dateFilter.ToUpper() == "P") ? item.PublishedDate >= From : item.CapturedDate >= dateFromDT)
      .Where(item => (dateFilter.ToUpper() == "P") ? item.PublishedDate <= dateTo : item.CapturedDate <= dateTo)
      .FirstOrDefault()

有人可以帮帮我吗?

Select * from Employees where PublishedDate = From and .......

2 个答案:

答案 0 :(得分:0)

我认为应该是这样的。

 Select Top 1 * from Employees 
     where 
(dateFilter = "P" COLLATE Latin1_General_CS_AS  AND PublishedDate >= From AND PublishedDate >=dateTo) 
OR 
(dateFilter != "P" COLLATE Latin1_General_CS_AS AND CapturedDate  >= dateFromDT AND CapturedDate  >= dateTo)

答案 1 :(得分:0)

你可以使用类似的东西:

select top 1 * 
  from employees 
 where (upper(DateFilter) = 'P' and PublishedDate >= From and PublishedDate <= dateTo)
    or (upper(DateFilter) <> 'P' and CapturedDate >= dateFromDT and CapturedDate <= dateTo)

如果DateFilter是表中的一列,那么最好跳过上面,因为它会降低性能(假设你有一个索引)。