I want to get data with a condition as lambda expression like in.
public IEnumerable<T> GetBy(Func<T, bool> condition)
{
var test = Context.Set<StateInfo>().Where(p => p.CustomerID != null && p.CustomerID == 5);
var test2= Context.Set<T>().Where(condition);
.
.
}
When I am looking the test object SQL query It use where clause in It. But the test2 object query is like only select * from table. It gets all data from DB then use when method in code side. How can I get data with where clause because test2 query takes a long time with big datas. Only difference is one of the codes with generic class but the sql queries different. Thanks.
Your condition is type of Func<T, bool>. When you look at overload of context.Set<T>().Where() you can see that, the one which takes Func<T, bool> returns IEnumerable<T> instaead of IQuerable<T>, because it takes all the data from the source, then applies filter. You should use Expression<Func<T, bool>> condition. Your method should be something like:
public IQueryable<T> GetBy<T>(Expression<Func<T, bool>> condition)
where T : class
{
return Context.Set<T>().Where(condition);
}
Note: If you want to return IEnumerable after filtering you can just keep it like:
public IEnumerable<T> GetBy<T>(Expression<Func<T, bool>> condition)
where T : class
{
// Should also work without AsEnumerable()
return Context.Set<T>().Where(condition).AsEnumerable();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With