简体   繁体   English

C#LINQ SQL合并转换

[英]c# linq sql coalesce conversion

I'm trying to convert an existing sql stored proc to use linq. 我正在尝试将现有的sql存储过程转换为使用linq。 The stored proc uses coalesce() while building up the 'where' clause. 存储的proc在建立“ where”子句时使用coalesce()。

Below is what I've tried. 以下是我尝试过的方法。

Can some give advice / other on the correct way to approach this conversion? 有人可以就正确的转换方式提供建议/其他吗?

------- sql ------- 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 ----- 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");

}

For me, using the ?? 对我来说,使用?? (c# equivalent of COALESCE ) might do the trick : (相当于COALESCE c#)可能会解决问题:

if(aDateMin.HasValue){
    query = query.Where(v => 
                        aDateMin.Value < v.a_end_dt ?? v.a_start_dt ?? new DateTime(1753, 1, 1));

Or another formulation : 或另一种说法:

query = query.Where(v => 
                        aDateMin.HasValue.Value < v.a_end_dt ?? v.a_start_dt ?? new DateTime(1753, 1, 1));

I've not tried it, but could you try something like: 我没有尝试过,但是您可以尝试以下操作:

var dt = new DateTime(1753, 1,1);
query = query.Where(v =>  (v.a_end_dt ?? v.a_start_dt ?? dt) >= aDateMin);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM