您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
Repository 在做查询的时候,如果查询条件多的话,linq查询表达式会写的很复杂,比如:
public IQueryable<Student> Get(int id, string name, string address, Status? status, DateTime createTime)
{
var query = _entities;
if(id != 0)
{
query = query.where(x => x.Id == id);
}
if(!string.IsNullOrWhiteSpace(name))
{
query = query.where(x => x.Name.Contains(name));
}
if(!string.IsNullOrWhiteSpace(address))
{
query = query.where(x => x.Address.Contains(address));
}
if(status.HasValue)
{
query = query.where(x => x.Status == status.Value);
}
if(createTime != null)
{
query = query.where(x => x.CreateTime == createTime);
}
// ...
return query;
}可以看到,查询条件多的话,我们会写很多的if判断,代码看起来很不美观,解决方式使用Expression<Func<T, bool>>,示例代码:
using System.Linq.Expressions;
public IQueryable<Student> Get(int id, string name, string address, Status? status, DateTime createTime)
{
Expression<Func<Student, bool>> studentFunc = x =>
(id == 0 || x.Id == id) &&
(string.IsNullOrWhiteSpace(name) || x.Name.Contains(name)) &&
(string.IsNullOrWhiteSpace(address) || x.Address.Contains(address)) &&
(!status.HasValue || x.Status == status.Value) &&
(createTime == null || x.CreateTime <= createTime);
return _entities.Where(studentFunc);
}生成示例sql代码:
SELECT `x`.`id`, `x`.`name`, `x`.`address`, `x`.`status`, `x`.`create_time` FROM `students` AS `x` WHERE (`x`.`id` = 2) AND (`x`.`status` = 0) AND (`x`.`create_time` == '2017-04-25T16:24:29.769+08:00'))
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。