目前我操作数据库主要用 EF和Dapper,EF不用说。相关的orm api 我们使用的很舒服,但是每次写Dapper 的时候我总是要写一坨SQL语句。典型的比如我要做一个查询。可能会写出一下代码:
var strText="" if(string.IsNullOrEmpty(name)) { strText="AND NAME LIKE '%name%'"; } if(age>0) { strText=$"AND AGE={age}"; }
所以也方便自己写一个相关的api,在工作里使用方便一点。
数据库操作符:= > < <> like between and or not (is null) (is not null) >= <= 所以我定义了一下枚举。
public enum QueryOper { /// <summary> /// 等于 /// </summary> Eq, /// <summary> /// 不等于 /// </summary> NotEq, /// <summary> /// 大于 /// </summary> Gt, /// <summary> /// 小于 /// </summary> Lt, /// <summary> /// 大于或等于 /// </summary> Ge, /// <summary> /// 小于或等于 /// </summary> Le, /// <summary> /// 左右模糊匹配 /// </summary> Like, /// <summary> /// 为空 /// </summary> IsNull, /// <summary> /// 不为空 /// </summary> IsNotNull, /// <summary> /// 区间 /// </summary> Between }
这些枚举最后会转为相应的 数据库操作符。
public static string ToString(QueryOper op) { switch (op) { case QueryOper.Eq: return " = "; case QueryOper.NotEq: return " <> "; case QueryOper.Gt: return " > "; case QueryOper.Lt: return " < "; case QueryOper.Ge: return " >= "; case QueryOper.Le: return " <= "; case QueryOper.Like: return " LIKE "; case QueryOper.IsNull: return " IS NULL "; case QueryOper.IsNotNull: return " IS NOT NULL "; case QueryOper.Between: return " BETWEEN "; default: throw new Exception("This method is not supported."); } }