- 增加 GlobalFilter.ApplyIf 创建动态过滤器;

This commit is contained in:
28810
2020-09-05 06:50:56 +08:00
parent 1bd4b7dbf1
commit beb2eaada2
4 changed files with 196 additions and 14 deletions

View File

@ -16,22 +16,35 @@ namespace FreeSql.Internal
{
public int Id { get; internal set; }
public string Name { get; internal set; }
internal Func<bool> Condition { get; set; }
public LambdaExpression Where { get; internal set; }
}
/// <summary>
/// 创建一个过滤器
/// 创建一个过滤器<para></para>
/// 提示:判断登陆身份,请参考资料 AsyncLocal
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="name">名字</param>
/// <param name="where">表达式</param>
/// <returns></returns>
public GlobalFilter Apply<TEntity>(string name, Expression<Func<TEntity, bool>> where)
public GlobalFilter Apply<TEntity>(string name, Expression<Func<TEntity, bool>> where) => ApplyIf(name, () => true, where);
/// <summary>
/// 创建一个动态过滤器,当 condition 返回值为 true 时才生效<para></para>
/// 场景:当登陆身份是管理员,则过滤条件不生效<para></para>
/// 提示:判断登陆身份,请参考资料 AsyncLocal
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="name">名字</param>
/// <param name="condition">委托,返回值为 true 时才生效</param>
/// <param name="where">表达式</param>
/// <returns></returns>
public GlobalFilter ApplyIf<TEntity>(string name, Func<bool> condition, Expression<Func<TEntity, bool>> where)
{
if (name == null) throw new ArgumentNullException(nameof(name));
if (where == null) return this;
_filters.TryGetValue(name, out var item);
if (item == null) item = new Item { Id = ++_id, Name = name };
if (item == null) item = new Item { Id = ++_id, Name = name, Condition = condition };
var newParameter = Expression.Parameter(typeof(TEntity), $"gf{_id}");
var newlambda = Expression.Lambda<Func<TEntity, bool>>(
@ -44,6 +57,6 @@ namespace FreeSql.Internal
}
public void Remove(string name) => _filters.TryRemove(name ?? throw new ArgumentNullException(nameof(name)), out var _);
public List<Item> GetFilters() => _filters.Values.OrderBy(a => a.Id).ToList();
public List<Item> GetFilters() => _filters.Values.Where(a => a.Condition?.Invoke() != false).OrderBy(a => a.Id).ToList();
}
}