使用Asp.Net Core MVC 开发项目实践[第四篇:基于EF Core的扩展2]
上篇我们说到了基于efcore的基础扩展,这篇我们讲解下基于实体结合拉姆达表达式的自定义更新以及删除数据.
先说下原理:其实通过实体以及拉姆达表达式生成sql语句去执行
第一种更新扩展:
自定义更新字段以及自定义扩展条件,请看下面的代码
1 /// <summary> 2 /// 自定义更新扩展 3 /// </summary> 4 /// <typeparam name="tentity"></typeparam> 5 /// <param name="context"></param> 6 /// <param name="fields">更新字段</param> 7 /// <param name="predicate">更新条件</param> 8 /// <returns></returns> 9 public static bool mangoupdate<tentity>(this dbcontext context, expression<func<tentity, bool>> fields, expression<func<tentity, bool>> predicate) where tentity : class, new() 10 { 11 tsqlassembledresult result = tsqlassembled.update<tentity>(fields, predicate); 12 context.database.executesqlcommand(result.sqlstr); 13 return context.savechanges() > 0 ? true : false; 14 }
从上面的方法中我们看到几个参数,第一个参数不必说,扩展方法第一个参数必须要的,我们重点讲清楚一下第二个和第三个参数.
参数:
expression<func<tentity, bool>> fields
表示实体中需要更新的字段,这里的参数要求的是一个拉姆达表达式,如下面的代码:
m => m.clickcount == m.clickcount + 1
这里就是更新字段clickcount+1的功能.
参数:
expression<func<tentity, bool>> predicate
表示更新条件,这个参数也是一个拉姆达表达式,如下面代码:
m => m.navigationid == navigationid
这里表示更新条件 navigationid指定值的数据库记录.
接下来我们看方法中的调用
tsqlassembled.update<tentity>(fields, predicate);
这个方法表示将参数解析成sql语句,我们看看这个方法的具体内容:
1 /// <summary> 2 /// 更新语句组装 3 /// </summary> 4 /// <typeparam name="tentity"></typeparam> 5 /// <param name="fields"></param> 6 /// <param name="predicate"></param> 7 /// <returns></returns> 8 public static tsqlassembledresult update<tentity>(expression<func<tentity, bool>> fields, expression<func<tentity, bool>> predicate) where tentity : class, new() 9 { 10 try 11 { 12 stringbuilder strbuilder = new stringbuilder(); 13 strbuilder.append("update "); 14 strbuilder.append(typeof(tentity).name); 15 strbuilder.append(" set "); 16 //解析需要更新的字段值 17 updatefieldbuilder updatefieldbuilder = new updatefieldbuilder(); 18 strbuilder.append(updatefieldbuilder.translate(fields)); 19 //解析条件 20 conditionbuilder conditionbuilder = new conditionbuilder(); 21 strbuilder.append(" where "); 22 strbuilder.append(conditionbuilder.translate(predicate)); 23 //处理结果返回 24 tsqlassembledresult result = new tsqlassembledresult(); 25 result.sqlparameters = null; 26 result.sqlstr = strbuilder.tostring(); 27 return result; 28 } 29 catch(exception ex) 30 { 31 return null; 32 throw ex; 33 } 34 }
ps:这个方法中用到的条件编译类以及字段编辑类我们将在文章底部贴出来.
第二种更新扩展:
/// <summary> /// 自定义更新扩展 /// </summary> /// <typeparam name="tentity"></typeparam> /// <param name="context"></param> /// <param name="entity">更新实体</param> /// <param name="predicate">更新条件</param> /// <returns></returns> public static bool mangoupdate<tentity>(this dbcontext context, tentity entity, expression<func<tentity, bool>> predicate) where tentity:class,new() { tsqlassembledresult result = tsqlassembled.update<tentity>(entity, predicate); context.database.executesqlcommand(result.sqlstr, result.sqlparameters); return context.savechanges() > 0 ? true : false; }
参数 tentity entity表示需要更新的实体
参数 expression<func<tentity, bool>> predicate 表示更新条件,示例如下:
m => m.navigationid == navigationid
tsqlassembled.update<tentity>(entity, predicate) 这个方法表示将参数解析成sql语句,我们看看这个方法的具体内容:
/// <summary> /// 更新语句组装 /// </summary> /// <typeparam name="tentity"></typeparam> /// <param name="entity"></param> /// <param name="predicate"></param> /// <returns></returns> public static tsqlassembledresult update<tentity>(tentity entity, expression<func<tentity, bool>> predicate) where tentity : class, new() { try { stringbuilder strbuilder = new stringbuilder(); strbuilder.append("update "); // type type = entity.gettype(); strbuilder.append(type.name); strbuilder.append(" set "); //处理实体类属性 propertyinfo[] properties = type.getproperties(); int index = 0; list<sqlparameter> sqlparameter = new list<sqlparameter>(); foreach (var property in properties) { object value = property.getvalue(entity, null); if (value != null) { if (index != 0) { strbuilder.append(","); } strbuilder.append(property.name); strbuilder.append("=@"); strbuilder.append(property.name); sqlparameter.add(new sqlparameter(property.name, value)); index++; } } //编译条件 conditionbuilder conditionbuilder = new conditionbuilder(); strbuilder.append(" where "); strbuilder.append(conditionbuilder.translate(predicate)); //处理结果返回 tsqlassembledresult result = new tsqlassembledresult(); result.sqlparameters = sqlparameter.toarray(); result.sqlstr = strbuilder.tostring(); return result; } catch (exception ex) { return null; throw ex; } }
ps:这里我们多了将实体反射获取需要更新的字段以及字段值.
第三种删除扩展:
自定删除条件,代码如下
1 /// <summary> 2 /// 自定义删除扩展 3 /// </summary> 4 /// <typeparam name="tentity"></typeparam> 5 /// <param name="context"></param> 6 /// <param name="predicate">删除条件</param> 7 /// <returns></returns> 8 public static bool mangoremove<tentity>(this dbcontext context,expression<func<tentity, bool>> predicate) where tentity : class,new() 9 { 10 tsqlassembledresult result = tsqlassembled.delete<tentity>(predicate); 11 context.database.executesqlcommand(result.sqlstr); 12 return context.savechanges() > 0 ? true : false; 13 }
参数expression<func<tentity, bool>> predicate表示为自定义条件,示例如下:
_dbcontext.mangoremove<entity.m_postsanswerrecords>(m => m.answerid == model.answerid && m.userid == model.userid);
ps:此段代码表示根据指定条件删除m_postsanswerrecords表中的记录
tsqlassembled.delete<tentity>(predicate)方法负责将指定条件编译成sql语句,代码如下:
/// <summary> /// 删除语句组装 /// </summary> /// <typeparam name="tentity"></typeparam> /// <param name="predicate"></param> /// <returns></returns> public static tsqlassembledresult delete<tentity>(expression<func<tentity, bool>> predicate) where tentity:class,new() { try { string tablename = typeof(tentity).name; //条件编译 conditionbuilder conditionbuilder = new conditionbuilder(); string conditionstr = conditionbuilder.translate(predicate); stringbuilder strbuilder = new stringbuilder(); strbuilder.append("delete from "); strbuilder.append(tablename); strbuilder.append(" where "); strbuilder.append(conditionstr); //处理结果返回 tsqlassembledresult result = new tsqlassembledresult(); result.sqlparameters = null; result.sqlstr = strbuilder.tostring(); return result; } catch(exception ex) { throw ex; } }
下面我们贴出字段以及条件的拉姆达表达式解析类:
条件解析类(conditionbuilder):
1 using system; 2 using system.collections.generic; 3 using system.text; 4 using system.linq; 5 using system.linq.expressions; 6 using system.reflection; 7 namespace mango.framework.efcore 8 { 9 public class conditionbuilder : expressionvisitor 10 { 11 12 stringbuilder strbuilder; 13 14 public conditionbuilder() 15 { 16 } 17 18 public string translate(expression expression) 19 { 20 this.strbuilder = new stringbuilder(); 21 this.visit(expression); 22 return this.strbuilder.tostring(); 23 } 24 25 private static expression stripquotes(expression e) 26 { 27 while (e.nodetype == expressiontype.quote) 28 { 29 e = ((unaryexpression)e).operand; 30 } 31 return e; 32 } 33 34 protected override expression visitbinary(binaryexpression b) 35 { 36 strbuilder.append("("); 37 this.visit(b.left); 38 switch (b.nodetype) 39 { 40 case expressiontype.andalso: 41 strbuilder.append(" and "); 42 break; 43 case expressiontype.orelse: 44 strbuilder.append(" or "); 45 break; 46 case expressiontype.equal: 47 strbuilder.append(" = "); 48 break; 49 case expressiontype.notequal: 50 strbuilder.append(" <> "); 51 break; 52 case expressiontype.lessthan: 53 strbuilder.append(" < "); 54 break; 55 case expressiontype.lessthanorequal: 56 strbuilder.append(" <= "); 57 break; 58 case expressiontype.greaterthan: 59 strbuilder.append(" > "); 60 break; 61 case expressiontype.greaterthanorequal: 62 strbuilder.append(" >= "); 63 break; 64 default: 65 throw new notsupportedexception(string.format("运算符{0}不支持", b.nodetype)); 66 } 67 if (b.right.nodetype != expressiontype.parameter&& b.right.nodetype == expressiontype.memberaccess) 68 { 69 lambdaexpression lambda = expression.lambda(b.right); 70 var fn = lambda.compile(); 71 this.visit(expression.constant(fn.dynamicinvoke(null), b.right.type)); 72 } 73 else 74 { 75 this.visit(b.right); 76 } 77 strbuilder.append(")"); 78 return b; 79 } 80 81 protected override expression visitconstant(constantexpression c) 82 { 83 switch (type.gettypecode(c.value.gettype())) 84 { 85 case typecode.boolean: 86 strbuilder.append(((bool)c.value) ? 1 : 0); 87 break; 88 case typecode.string: 89 strbuilder.append("'"); 90 strbuilder.append(c.value); 91 strbuilder.append("'"); 92 break; 93 case typecode.object: 94 throw new notsupportedexception(string.format("常量{0}不支持", c.value)); 95 default: 96 strbuilder.append(c.value); 97 break; 98 } 99 return c; 100 } 101 102 protected override expression visitmember(memberexpression m) 103 { 104 if (m.expression != null && m.expression.nodetype == expressiontype.parameter) 105 { 106 strbuilder.append(m.member.name); 107 return m; 108 } 109 else if (m.expression != null && m.expression.nodetype == expressiontype.constant) 110 { 111 lambdaexpression lambda = expression.lambda(m); 112 var fn = lambda.compile(); 113 this.visit(expression.constant(fn.dynamicinvoke(null), m.type)); 114 return m; 115 } 116 throw new notsupportedexception(string.format("成员{0}不支持", m.member.name)); 117 } 118 } 119 }
更新字段解析类(updatefieldbuilder):
1 using system; 2 using system.collections.generic; 3 using system.text; 4 using system.linq; 5 using system.linq.expressions; 6 using system.reflection; 7 namespace mango.framework.efcore 8 { 9 public class updatefieldbuilder : expressionvisitor 10 { 11 stringbuilder strbuilder; 12 public string translate(expression expression) 13 { 14 this.strbuilder = new stringbuilder(); 15 this.visit(expression); 16 return this.strbuilder.tostring(); 17 } 18 19 private static expression stripquotes(expression e) 20 { 21 while (e.nodetype == expressiontype.quote) 22 { 23 e = ((unaryexpression)e).operand; 24 } 25 return e; 26 } 27 protected override expression visitbinary(binaryexpression b) 28 { 29 //strbuilder.append("("); 30 this.visit(b.left); 31 switch (b.nodetype) 32 { 33 case expressiontype.equal: 34 strbuilder.append("="); 35 break; 36 case expressiontype.andalso: 37 strbuilder.append(","); 38 break; 39 case expressiontype.add: 40 strbuilder.append("+"); 41 break; 42 case expressiontype.subtract: 43 strbuilder.append("-"); 44 break; 45 default: 46 throw new notsupportedexception(string.format("运算符{0}不支持", b.nodetype)); 47 } 48 this.visit(b.right); 49 //strbuilder.append(")"); 50 return b; 51 } 52 53 protected override expression visitconstant(constantexpression c) 54 { 55 switch (type.gettypecode(c.value.gettype())) 56 { 57 case typecode.boolean: 58 strbuilder.append(((bool)c.value) ? 1 : 0); 59 break; 60 case typecode.string: 61 strbuilder.append("'"); 62 strbuilder.append(c.value); 63 strbuilder.append("'"); 64 break; 65 case typecode.object: 66 throw new notsupportedexception(string.format("常量{0}不支持", c.value)); 67 default: 68 strbuilder.append(c.value); 69 break; 70 } 71 return c; 72 } 73 74 protected override expression visitmember(memberexpression m) 75 { 76 if (m.expression != null && m.expression.nodetype == expressiontype.parameter) 77 { 78 strbuilder.append(m.member.name); 79 return m; 80 } 81 throw new notsupportedexception(string.format("成员{0}不支持", m.member.name)); 82 } 83 } 84 }
到此本篇章完成,更详细的代码请下载源代码查看.