C# 表达式树生成 Sql/Where 查询语句

表达式树生成 Sql 语句的难点在于 Where 条件,WhereTranslator 支持 IndexOf,Contains,StartsWith 以及 EndsWith 四个函数,同时支持生成参数形式的 Sql 语句。

https://gitee.com/snipen/Helper.Core.Library/blob/master/DataBaseHelper.cs

测试代码如下:

string organizationCode = "abc";
string organizationCode2 = "efg";
List<string> organizationCodeList = new List<string>()
{
    organizationCode, organizationCode2
};
Expression<Func<DTUserModel, bool>> expression = p => !organizationCodeList.Contains(p.OrganizationCode) &&
        p.DeleteStatus == p.DeleteStatus &&
        p.NickName.IndexOf("dddd") > 0 && 
        p.NickName.Contains("aaaaa") && 
        (p.IdentityID == 1 || p.IdentityID == 2) && 
        (p.OrganizationCode.StartsWith(organizationCode) || p.OrganizationCode.EndsWith(organizationCode2));

生成 SQL 语句如下:

OrganizationCode not in ('abc','efg') and DeleteStatus = @DeleteStatus and CHARINDEX('dddd', NickName) > 0 and NickName like '%aaaaa%' and (IdentityID = 1 or IdentityID = 2) and (OrganizationCode like 'abc%' or OrganizationCode like '%efg' )

管理员

转载请注明出处!如果本博文或者本站对您(网站)的内容/素材构成侵权,请第一时间与本博主联系!

Press ESC to close