public IQueryable<UserLogin> GetAll() { return _userRepository.GetAll(); }
public IQueryable<UserLogin> FilterUsers(int? roleId, string userName, bool? enabled) { Expression<Func<UserLogin, bool>> expression = u => (!roleId.HasValue || u.Roles.Select(r => r.Id).Count(t => t == roleId.Value) > 0) && (string.IsNullOrWhiteSpace(userName) || u.UserName.Contains(userName.Trim())) && (!enabled.HasValue || u.Enabled == enabled.Value); return GetAll().Where(expression); }
这样的查询报错,甚至这样也会报错
return GetAll().Where(u => !enabled.HasValue || u.Enabled == enabled.Value);
到底这个该怎么写呢?
public class UserLogin : BaseEntity { private IList<Role> _roles; public UserLogin() { _roles = new List<Role>(); } public virtual int Id { get; set; } /// <summary> /// 用户名 /// </summary> public virtual string UserName { get; set; } /// <summary> /// Email /// </summary> public virtual string Email { get; set; } public virtual string Password { get; set; } /// <summary> /// 是否禁用 /// </summary> public virtual bool Enabled { get; set; } public virtual DateTime CreateTime { get; set; } public virtual UserInfo UserInfo { get; set; } public virtual IList<Role> Roles { get { return _roles; } set { _roles = value; } } }
为什么这么写就没问题了
return GetAll().Where(u => (enabled == null || u.Enabled == enabled) && (string.IsNullOrWhiteSpace(userName) || u.UserName.Contains(userName)) && (roleId == null || u.Roles.Count(r => r.Id == roleId) > 0));
到底是什么原因呢?