5

How to write correct Linq expression used in generic for condition "where"

public static class ConStr
{
    public static MySqlConnection Conn()
    {
        return new MySqlConnection(ConfigurationManager.ConnectionStrings["DBCN"].ConnectionString);
    }

}

Repositor.cs

private IDbConnection cn;

public IEnumerable<TEntity> FilterBy(Expression<Func<TEntity, bool>> expression)
{
     using(cn = ConStr.Conn())
     {
        return cn.GetAll<TEntity>(null).Where(expression); <--error does not contain definition of where
     }

 }

but this with Linq expression will run

using (IDbConnection cn = ConStr.Conn()) 
{
    var que = cn.GetAll<Cause>(null).Where(x=>x.cause_id == 1);            
    bool dbIE = Utils.IsAny<Cause>(que);
    if (dbIE == true)
    {
        DGRID.DataSource = que;
    }
    else 
    {
        MessageBox.Show("Sorry No Value");
    }
}  
jake talledo
  • 610
  • 11
  • 24
  • Most likely your `GetAll` is returning `IEnumerable` which does not have `Where` with `Expression`, but `Func`. Visually there is no difference between implicit `Expression>` and `Func<...>`, that's why your second snippet compiles. – Ivan Stoev Apr 23 '16 at 11:33
  • Instead of implementing IEnumerable you can put all items in a List Collection. A List Collection is IEnumerable so you don't have to write you own implementation. – jdweng Apr 23 '16 at 11:38
  • @IvanStoev ah I see thanks a lot I will try to change – jake talledo Apr 23 '16 at 11:39
  • Note your `FilterAll` method will most likely not work given that the connection is closed by the time you return the `IQueryable` implementation. – casperOne Apr 23 '16 at 11:47
  • @casperOne this depends on how `GetAll` extension implemented – Maxim Kosov Apr 23 '16 at 11:52
  • @casperOne opps I forgot Im using Dapper the GetAll() is in Dapper Extension – jake talledo Apr 23 '16 at 11:57
  • @maxim see this previous version which my comment was based on: http://stackoverflow.com/revisions/36810185/3 – casperOne Apr 23 '16 at 11:58

1 Answers1

4

Where for IEnumerable<T> does not contains overload that takes Expression. To use Where with Expression you must change the result of GetAll to IQueryable. For your particular case you can just change Expression<Func<TEntity, bool>> expression to Func<TEntity, bool> expression and everything should work.

Maxim Kosov
  • 1,930
  • 10
  • 19
  • Thanks so Func expression -> is for IEnumerable and for is for IQueryable is -> Expression> expression. – jake talledo Apr 23 '16 at 11:43
  • 1
    There is also `AsQueryable()` extension on `IEnumerable` type which casts your `IEnumerable` to `IQueryable`, but I don't really know why would you want to use this in production..Most of the time simple `Func` or `Action` would be enough and if you want to use `Expression` you need to know why – Maxim Kosov Apr 23 '16 at 11:47