Using Entity Framework 4.3 in one of my data access classes I have generic a function like this
public List<Company> Query(Func<Company, bool> expression)
{
return MyDbContext.Instance().Company.Where(expression).ToList();
}
I use it from the bussines layer classes as MyDAL.Query(a => a.Name.Contains(textToSearch)).
Despite ofEntity Framework return the correct results, I don’t know why it instead of generate a Sql query sentence with Where clause like “Where name like ‘%’ + textToSearch + ‘%'”, It generates a sql query sentence without a where clause query all the table rows. Obviously this is very inneficient.
By the other way if in my data access clases I write a method like this:
public List<Company> GetLikeName(string textToSearch)
{
return MyDbContext.Instance().Company.Where(a => a.Contains(textToSearch)).ToList();
}
It generates correctly a Sql with where like clause.
Why If I use my generic query to retrieve results from database especifying the expression to query from my bussiness classes it generates a Sql sentence without where clause?
Thanks
You need to pass the expression parameter as an
Expression<>:If you just pass a
Func<>, thenIEnumerable.Whereis called instead ofIQueryable.Where, and it runs in code, not in SQL.