网上找的源码,但是博主说有bug 让自己调试。这个是我经过多次修改后的代码,可以直接用

 public static class LambdaToSqlHelper
{ #region 基础方法 #region 获取条件语句方法 private static string GetWhereSql<T>(Expression<Func<T, bool>> func, List<ParMODEL> parModelList) where T : class
{
string res = "";
if (func.Body is BinaryExpression)
{
//起始参数 BinaryExpression be = ((BinaryExpression)func.Body);
res = BinarExpressionProvider(be.Left, be.Right, be.NodeType, parModelList);
}
else if (func.Body is MethodCallExpression)
{
MethodCallExpression be = ((MethodCallExpression)func.Body);
res = ExpressionRouter(func.Body, parModelList);
}
else
{
res = " ";
} return res;
} #endregion 获取条件语句方法 #region 获取排序语句 order by private static string GetOrderSql<T>(Expression<Func<T, object>> exp) where T : class
{
var res = "";
if (exp.Body is UnaryExpression)
{
UnaryExpression ue = ((UnaryExpression)exp.Body);
List<ParMODEL> parModelList = new List<ParMODEL>();
res = "order by `" + ExpressionRouter(ue.Operand, parModelList).ToLower() + "`";
}
else
{
MemberExpression order = ((MemberExpression)exp.Body);
res = "order by `" + order.Member.Name.ToLower() + "`";
}
return res;
} #endregion 获取排序语句 order by #endregion 基础方法 #region 底层 public static bool In<T>(this T obj, T[] array)
{
return true;
} public static bool NotIn<T>(this T obj, T[] array)
{
return true;
} public static bool Like(this string str, string likeStr)
{
return true;
} public static bool NotLike(this string str, string likeStr)
{
return true;
} private static string GetValueStringByType(object oj)
{
if (oj == null)
{
return "null";
}
else if (oj is ValueType)
{
return oj.ToString();
}
else if (oj is string || oj is DateTime || oj is char)
{
return string.Format("'{0}'", oj.ToString());
}
else
{
return string.Format("'{0}'", oj.ToString());
}
} private static string BinarExpressionProvider(Expression left, Expression right, ExpressionType type, List<ParMODEL> parModelList)
{
string sb = "(";
//先处理左边
string reLeftStr = ExpressionRouter(left, parModelList);
sb += reLeftStr; sb += ExpressionTypeCast(type); //再处理右边
string tmpStr = ExpressionRouter(right, parModelList);
if (tmpStr == "null")
{
if (sb.EndsWith(" ="))
{
sb = sb.Substring(0, sb.Length - 2) + " is null";
}
else if (sb.EndsWith("<>"))
{
sb = sb.Substring(0, sb.Length - 2) + " is not null";
}
}
else
{
//添加参数
sb += tmpStr;
} return sb += ")";
} private static string ExpressionRouter(Expression exp, List<ParMODEL> parModelList)
{
string sb = string.Empty; if (exp is BinaryExpression)
{
BinaryExpression be = ((BinaryExpression)exp);
return BinarExpressionProvider(be.Left, be.Right, be.NodeType, parModelList);
}
else if (exp is MemberExpression)
{
MemberExpression me = ((MemberExpression)exp);
if (!exp.ToString().StartsWith("value"))
{
return me.Member.Name;
}
else
{
var result = Expression.Lambda(exp).Compile().DynamicInvoke();
if (result == null)
{
return "null";
}
else if (result is ValueType)
{
ParMODEL p = new ParMODEL();
p.name = "par" + (parModelList.Count + 1);
p.value = result.ToString().ToIntByStr();
parModelList.Add(p);
//return ce.Value.ToString();
return "@par" + parModelList.Count;
}
else if (result is string || result is DateTime || result is char)
{
ParMODEL p = new ParMODEL();
p.name = "par" + (parModelList.Count + 1);
p.value = result.ToString();
parModelList.Add(p);
//return string.Format("'{0}'", ce.Value.ToString());
return "@par" + parModelList.Count;
}
else if (result is int[])
{
var rl = result as int[];
StringBuilder sbIntStr = new StringBuilder();
foreach (var r in rl)
{
ParMODEL p = new ParMODEL();
p.name = "par" + (parModelList.Count + 1);
p.value = r.ToString().ToIntByStr();
parModelList.Add(p);
//return string.Format("'{0}'", ce.Value.ToString());
sbIntStr.Append("@par" + parModelList.Count + ",");
}
return sbIntStr.ToString().Substring(0, sbIntStr.ToString().Length - 1);
}
else if (result is string[])
{
var rl = result as string[];
StringBuilder sbIntStr = new StringBuilder();
foreach (var r in rl)
{
ParMODEL p = new ParMODEL();
p.name = "par" + (parModelList.Count + 1);
p.value = r.ToString();
parModelList.Add(p);
//return string.Format("'{0}'", ce.Value.ToString());
sbIntStr.Append("@par" + parModelList.Count + ",");
}
return sbIntStr.ToString().Substring(0, sbIntStr.ToString().Length - 1);
}
}
}
else if (exp is NewArrayExpression)
{
NewArrayExpression ae = ((NewArrayExpression)exp);
StringBuilder tmpstr = new StringBuilder();
foreach (Expression ex in ae.Expressions)
{
tmpstr.Append(ExpressionRouter(ex, parModelList));
tmpstr.Append(",");
}
//添加参数 return tmpstr.ToString(0, tmpstr.Length - 1);
}
else if (exp is MethodCallExpression)
{
MethodCallExpression mce = (MethodCallExpression)exp;
string par = ExpressionRouter(mce.Arguments[0], parModelList);
if (mce.Method.Name == "Like")
{
//添加参数用
return string.Format("({0} like {1})", par, ExpressionRouter(mce.Arguments[1], parModelList));
}
else if (mce.Method.Name == "NotLike")
{
//添加参数用
return string.Format("({0} Not like {1})", par, ExpressionRouter(mce.Arguments[1], parModelList));
}
else if (mce.Method.Name == "In")
{
//添加参数用
return string.Format("{0} In ({1})", par, ExpressionRouter(mce.Arguments[1], parModelList));
}
else if (mce.Method.Name == "NotIn")
{
//添加参数用
return string.Format("{0} Not In ({1})", par, ExpressionRouter(mce.Arguments[1], parModelList));
}
}
else if (exp is ConstantExpression)
{
ConstantExpression ce = ((ConstantExpression)exp);
if (ce.Value == null)
{
return "null";
}
else if (ce.Value is ValueType)
{
ParMODEL p = new ParMODEL();
p.name = "par" + (parModelList.Count + 1);
p.value = ce.Value.ToString().ToIntByStr();
parModelList.Add(p);
//return ce.Value.ToString();
return "@par" + parModelList.Count;
}
else if (ce.Value is string || ce.Value is DateTime || ce.Value is char)
{
ParMODEL p = new ParMODEL();
p.name = "par" + (parModelList.Count + 1);
p.value = ce.Value.ToString();
parModelList.Add(p);
//return string.Format("'{0}'", ce.Value.ToString());
return "@par" + parModelList.Count;
} //对数值进行参数附加
}
else if (exp is UnaryExpression)
{
UnaryExpression ue = ((UnaryExpression)exp); return ExpressionRouter(ue.Operand, parModelList);
}
return null;
} private static string ExpressionTypeCast(ExpressionType type)
{
switch (type)
{
case ExpressionType.And:
case ExpressionType.AndAlso:
return " AND "; case ExpressionType.Equal:
return " ="; case ExpressionType.GreaterThan:
return " >"; case ExpressionType.GreaterThanOrEqual:
return ">="; case ExpressionType.LessThan:
return "<"; case ExpressionType.LessThanOrEqual:
return "<="; case ExpressionType.NotEqual:
return "<>"; case ExpressionType.Or:
case ExpressionType.OrElse:
return " Or "; case ExpressionType.Add:
case ExpressionType.AddChecked:
return "+"; case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
return "-"; case ExpressionType.Divide:
return "/"; case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
return "*"; default:
return null;
}
} #endregion 底层
} public class SqlParMODEL
{
public string sql { set; get; } private List<ParMODEL> parList { set; get; }
} public class ParMODEL
{
public string name { set; get; } public object value { set; get; }
}

where条件的lambda转化为sql语句的更多相关文章

  1. Lambda表达式转SQL语句类库

    /* 作者:道法自然   * 个人邮件:myyangbin@sina.cn * 2014-10-1 */ Lambda表达式转SQL语句类库源码下载:http://download.csdn.net/ ...

  2. C# Expression 树转化为SQL语句(一)

    sql有有四中基本语句,分别是增删改查,在建立model后如何生成这四中sql语句,降低开发时间. 我们先模拟出一张学生表: public class Student { public int id ...

  3. Hql语句转化为sql语句中文乱码问题

    刚刚学习Hql语句就出现这一的问题,百度半天终于解决了,总结一下解决的方案: 出现中文乱码最可能的原因是hibernate配置文件配置的问题 1.检查url路径是否指定字符集为UTF-8 <pr ...

  4. C#实现把String字符串转化为SQL语句中的In后接的参数

    实现把String字符串转化为In后可用参数代码: public string StringToList(string aa) { string bb1 = "("; if (!s ...

  5. 根据多表条件更新表.............. 一条sql语句.............

    CREATE TABLE a( NAME INT, age int ); CREATE TABLE b( height INT, weight int ); ,); ,); SELECT * FROM ...

  6. MyBatis中动态SQL语句完成多条件查询

    一看这标题,我都感觉到是mybatis在动态SQL语句中的多条件查询是多么的强大,不仅让我们用SQL语句完成了对数据库的操作:还通过一些条件选择语句让我们SQL的多条件.动态查询更加容易.简洁.直观. ...

  7. 理想中的SQL语句条件拼接方式 (二)

    问题以及想要的效果,不重复叙述,如果需要的请先看 理想中的SQL语句条件拼接方式 . 效果 现在有2个类映射数据库的2张表,结构如下: public class User { public int U ...

  8. Python使用sql语句对mysql数据库多条件模糊查询

    1 def find_worldByName(c_name,continent): 2 print(c_name) 3 print(continent) 4 sql = " SELECT * ...

  9. 数据库-转换sql语句

    文章描述:主要说明转换成SQL语句的过程.----必要信息(数据库名,表名,条件)转换成SQL语句 一些界面上数据增删改查的操作往往只需要输入一数据库名,表名,加条件就可以进行数据查询了,在这背后是怎 ...

随机推荐

  1. JSON lib 里JsonConfig详解

    一,setCycleDetectionStrategy 防止自包含 /** * 这里测试如果含有自包含的时候需要CycleDetectionStrategy */ public static void ...

  2. 《JavaScript高级程序设计》读书笔记 ---RegExp 类型

    ECMAScript 通过RegExp 类型来支持正则表达式.使用下面类似Perl 的语法,就可以创建一个正则表达式.var expression = / pattern / flags ; 其中的模 ...

  3. scala调用外部命令

     scala调用外部命令 1.  导入sys.process包 2. 调用方式:" 外部命令 " !     双引号内+外部命令+感叹号 例:     scala调用外部命令工作原 ...

  4. css ::before和::after伪元素的用法

    css ::before和::after伪元素的用法:http://blog.dimpurr.com/css-before-after/

  5. js 上传图片预览

    <script language='javascript'> function show(){ var p=document.getElementById("file1" ...

  6. ios空模板配置

    ios之Xcode6如何手动创建空工程模板 1.首先创建Single View Application 2.然后找到工程目录->Supporting Files ——>找到 info.pl ...

  7. putty完全使用手册--多窗口---git提交---连接数据库--自动日志显示

    01 putty dev 192.168.3.38 02 cd /home/gongfu/tripb/cranedev02.1 git status git add git commit git pu ...

  8. C语言 - 预编译

    1.#ifdef 实现 与 或#if (defined SIMULATION) && (defined _FMM_LOG)#endif #if (!defined A) || (!de ...

  9. protected-broadcast的作用

    protected-broadcast(暂时从网上搜到这么多,也不知对错,先留着) “保护性广播”,在一些AndroidManifest.xml中的一级标记<protected-broadcas ...

  10. NSBundle、UIImageView和UIButton对比、Xcode文档安装路径、Xcode模拟器安装路径

    1.NSBundle1> 一个NSBundle代表一个文件夹,利用NSBundle能访问对应的文件夹2> 利用mainBundle就可以访问软件资源包中的任何资源3> 模拟器应用程序 ...