Reputation: 1242
I have a generic repository, something like this:
public IEnumerable<T> SelectAll()
{
return table.ToList();
}
public T SelectByID(object id)
{
return table.Find(id);
}
public void Insert(T obj)
{
table.Add(obj);
}
This works fine for the basic CRUD, but now I need to search an entity (table) against an user entered searchterm. Is it at all possible to do it with something like:
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();
}
Upvotes: 3
Views: 1557
Reputation: 1242
This is what I am using now:
public IEnumerable<T> SelectAll(Expression<Func<T, bool>> predicate)
{
IEnumerable<T> searchResult = context.Set<T>().Where(predicate);
return searchResult;
}
And the method call:
var lstResult = objRepo.SelectAll(x=>x.ColumnName.Contains(searchText));
Upvotes: 0
Reputation: 2232
Use a Lambda Expression as the argument
public virtual async Task<List<T>> SearchBy(Expression<Func<Table, bool>> searchBy)
{
return await _ctx.Set<Table>().Where(searchBy).ToListAsync();
}
with this, you will call the search with a table expression argument returning a boolen
Upvotes: 4