简体   繁体   中英

Passing predicate to LINQ where clause

Hey I have following code:

    Func<Assoc, bool> predicate = (x) => 
    (
        !String.IsNullOrWhiteSpace(version) ? x.Version.Contains(version) : x.Version != null

    );

    var assocs = _context.Assoc
                    .Where(x => x.Model == model)
                    .Where(predicate)
                    ;

But it doesn't work. If I try to execute this server gives me Internal Server Exception but if I change this to

var assocs = _context.Assoc
      .Where(x => x.Model == model)
      .Where(x => x.Version.Contains(version))
;

it works as I expect.

Why is that?

Is it possible to get preview of Linq generated query?

Using LINQKit you can create predicates that will be expanded for you so you can use them in IQueryable expressions, but you don't need that for just excluding version testing.

var assocs = _context.Assoc
             .Where(x => x.Model == model);
if (!String.IsNullOrWhiteSpace(version))
    assocs = assocs.Where(x.Version.Contains(version));

becuse the EF can translate Contains method to sql ( Version LIKE '%@version%' ), but no evaluate your "external" function.

if you load the result to memroy (by export method as ToList() ) you can do it as linq2object:

var assocs = _context.Assoc.ToList()
                .Where(x => x.Model == model)
                .Where(predicate);

My code shows and illustrates but it is definitely not recommended, because it is better to question the DB than to work on memory.

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