【发布时间】:2020-03-15 06:30:28
【问题描述】:
我想创建一个通用服务,它仅通过其修饰属性(通过自定义属性)在特定实体中搜索 我尝试使用表达式来做到这一点,但我认为我遗漏了一些东西。 这是一个示例代码:
服务
public class MyService<TEntity>
where TEntity: class
{
private readonly MyContext context;
public MyService()
{
this.context = new MyContext();
}
private Func<TEntity, string, bool> searchFunc = (e, search) =>
{
var type = typeof(TEntity);
var props = type.GetProperties().Where(p => p.GetCustomAttributes(typeof(SearchPropertyAttribute), true).Any());
Expression expression = Expression.Constant(false);
foreach (var prop in props)
{
expression = Expression.MakeBinary(ExpressionType.Or,
expression,
Expression.MakeBinary(ExpressionType.Equal,
Expression.Property(Expression.Constant(e), prop.Name),
Expression.Constant(search)));
}
var delegateFunc = Expression.Lambda<Func<TEntity, string, bool>>(expression).Compile();
return delegateFunc(e, search);
};
/// <summary>
/// searches in specified entity set the given string using only decorated properties.
/// </summary>
public List<TEntity> Find(string search)
{
var list = this.context.Set<TEntity>().Where(e => searchFunc(e as TEntity, search));
return list.ToList() as List<TEntity>;
}
}
实体
public class MyEntity
{
[SearchProperty]
public string FirstName { get; set; }
[SearchProperty]
public string LastName { get; set; }
public string Description { get; set; }
}
我只想限制搜索由 SearchProperty 属性修饰的属性 谢谢
【问题讨论】:
标签: c# entity-framework generics asp.net-core-webapi