我有一个通用的存储库,如下所示:
public IEnumerable<T> SelectAll()
{
return table.ToList();
}
public T SelectByID(object id)
{
return table.Find(id);
}
public void Insert(T obj)
{
table.Add(obj);
}
这适用于基本的CRUD,但现在我需要针对用户输入的searchterm搜索实体(表)。是否可以通过以下方式实现:
public IEnumerable<T> SelectAll(T obj, string searchText, string columnName)
{
// I am not sure what code to write here... It should give me all the records that contain the search term.
// I was thinking something like this could be made to work...but I need help with it.
return table.GetType().GetProperty(columnName).GetValue())ToList();
}
答案 0 :(得分:1)
使用Lambda表达式作为参数
public virtual async Task<List<T>> SearchBy(Expression<Func<Table, bool>> searchBy)
{
return await _ctx.Set<Table>().Where(searchBy).ToListAsync();
}
这样,您将使用表表达式参数调用搜索返回boolen
答案 1 :(得分:0)
这就是我现在使用的:
public IEnumerable<T> SelectAll(Expression<Func<T, bool>> predicate)
{
IEnumerable<T> searchResult = context.Set<T>().Where(predicate);
return searchResult;
}
方法调用:
var lstResult = objRepo.SelectAll(x=>x.ColumnName.Contains(searchText));