简体   繁体   中英

Dynamic change of Where filters in linq

I'm trying to do some code optimization in my app and replace several methods that do same thing with one. I have this linq that i need to execute with various filters, but i get design time errors in .Where(filter) part

        Expression<Func<dbTable, bool>> filter;
        switch (i)
        {
            case 1: filter = (p => p.f1 == ExternalParam);
            case 2: filter = (p => p.f2 == ExternalParam);
        }

        var ds = (from tbl in dbEntities.dbTable

                  orderby tbl.f1

                  select new
                  {
                      f1 = tbl.f1,
                      f2 = tbl.f2,
                      f3 = tbl.f3,
                      f4 = tbl.f4,

                  }
                      ).Where(filter);

Errors are

Error   1   'System.Linq.IQueryable<AnonymousType#1>' does not contain a definition for 'Where' and the best extension method overload 'System.Linq.Queryable.Where<TSource>(System.Linq.IQueryable<TSource>, System.Linq.Expressions.Expression<System.Func<TSource,int,bool>>)' has some invalid arguments    
Error   2   Argument 2: cannot convert from 'System.Linq.Expressions.Expression<System.Func<AppNameSpace.dbTable,bool>>' to 'System.Linq.Expressions.Expression<System.Func<AnonymousType#1,int,bool>>' 

Can someone help with this?

Well, your Expression is of type Expression<dbTable, bool>

and you try to apply it to an anonymous type (when you do the select new , you're projecting to an anonymous type), which is... not a dbTable

So you should apply your predicate to an IQueryable<dbTable> : dbEntities.dbTable should be of that type.

    var ds = from tbl in dbEntities.dbTable.Where(filter)

              orderby tbl.f1

              select new
              {
                  f1 = tbl.f1,
                  f2 = tbl.f2,
                  f3 = tbl.f3,
                  f4 = tbl.f4,

              };

By the way, I find it easier to avoid mixing syntaxes when not needed.

var ds = dbEntities.dbTable.Where(filter)
                           .OrderBy(m => m.f1)
                           .Select(m => new {
                              tbl.f1,
                              tbl.f2,
                              tbl.f3,
                              tbl.f4
                            });

But this part is just a personal PoV.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM