搜索条件映射成Sql语句有2种写法,第一种是把输入条件参数转成Expression表达式树,适合简单的Sql查询,第二种是拼接原生Sql,适合复杂的Sql查询。
1 ) 第一种转成Expression表达式树写法
private Expression<Func<PositionEntity, bool>> ListFilter(PositionListParam param) { var expression = LinqExtensions.True<PositionEntity>(); if (param != null) { if (!string.IsNullOrEmpty(param.PositionName)) { expression = expression.And(t => t.PositionName.Contains(param.PositionName)); } if (!string.IsNullOrEmpty(param.PositionIds)) { long[] positionIdArr = CommonHelper.SplitToArray<long>(param.PositionIds, ','); expression = expression.And(t => positionIdArr.Contains(t.Id.Value)); } } return expression; }
调用方法如下:
public async Task<List<PositionEntity>> GetPageList(PositionListParam param, Pagination pagination) { var expression = ListFilter(param); var list = await this.BaseRepository().FindList(expression, pagination); return list.ToList(); }
2 ) 第二种拼接原生Sql写法
private List<DbParameter> ListFilter(LogApiListParam param, StringBuilder strSql) { strSql.Append(@"SELECT a.id as Id, a.base_modify_time as BaseModifyTime, a.base_modifier_id as BaseModifierId, a.log_status as LogStatus, FROM sys_log_api a LEFT JOIN sys_user b ON a.base_modifier_id = b.id LEFT JOIN sys_department c ON b.department_id = c.id WHERE 1 = 1"); var parameter = new List<DbParameter>(); if (param != null) { if (!string.IsNullOrEmpty(param.UserName)) { strSql.Append(" AND b.user_name like @UserName"); parameter.Add(DbParameterExtension.CreateDbParameter("@UserName", '%' + param.UserName + '%')); } } return parameter; }
调用方法如下:
public async Task<List<LogApiEntity>> GetPageList(LogApiListParam param, Pagination pagination) { var strSql = new StringBuilder(); List<DbParameter> filter = ListFilter(param, strSql); var list = await this.BaseRepository().FindList<LogApiEntity>(strSql.ToString(), filter.ToArray(), pagination); return list.ToList(); }