我试图将现有的sql存储过程转换为使用linq。存储的proc使用coalesce(),同时构建'其中'条款。
以下是我尝试过的内容。
有些人可以就正确的方式提供建议吗?
------- sql
if @a is not null
set @WhereClause = @WhereClause + ' and v.a_number = ''' + @a + ''''
if @b is not null
set @WhereClause = @WhereClause + ' and v.b_number = ''' + @b + ''''
if @aDateMin is not null
set @WhereClause = @WhereClause + ' and coalesce(v.a_end_dt, v.a_start_dt, ''1/1/1753'')
>= ''' + convert(varchar(10), @aDateMin, 101) + ''''
if @aDateMax is not null
set @WhereClause = @WhereClause + ' and coalesce(v.a_start_dt, v.a_end_dt, ''12/31/9999'')
<= ''' + convert(varchar(10), @aDateMax, 101) + ''''
set @Sql = from Results v
@WhereClause ;';
--print @Sql
exec sp_executesql @Sql
----- linq
var aNumber = "";
var bNumber = "";
DateTime? aDateMin = null;
DateTime? aDateMax = null;
var query = from v in searchResults
select v;
if(!String.IsNullOrEmpty(aNumber )){
query = query.Where(v => v.a_number == aNumber);
}
if(!String.IsNullOrEmpty(bNumber)){
query = query.Where(v => v.b_number == bNumber);
}
// this is where I'm having issue with the conversion.
if(aDateMin.HasValue){
query = query.Where(v =>
v.a_end_dt.HasValue ? v.a_end_dt >= aDateMin : v.a_start_dt.HasValue ? v.a_start_dt <= aDateMin : "1/1/1753");
}
答案 0 :(得分:1)
对我来说,使用??
(c#等效于COALESCE
)可能会有所帮助:
if(aDateMin.HasValue){
query = query.Where(v =>
aDateMin.Value < v.a_end_dt ?? v.a_start_dt ?? new DateTime(1753, 1, 1));
或另一种表述:
query = query.Where(v =>
aDateMin.HasValue.Value < v.a_end_dt ?? v.a_start_dt ?? new DateTime(1753, 1, 1));
答案 1 :(得分:1)
我没有尝试过,但你可以试试像:
var dt = new DateTime(1753, 1,1);
query = query.Where(v => (v.a_end_dt ?? v.a_start_dt ?? dt) >= aDateMin);