0

I have a linq query which I want to add some additional, optional WHERE conditions to using LinqKit Predicate Builder. However, I an struggling to get the additional predicate to work

This is my initial query:

var query = (from OP in ctx.OrganisationProducts
             where OP.OrganisationID == orgID
             orderby OP.Product.Name, OP.Product.VersionName
             select OP).Include("Product");

As you can see, there is JOIN in there. I then wish to add additional predicates if required:

if(!includeDisabledP42Admin || !includeDisabledOrgAdmin)
{
    var pred = PredicateBuilder.True<OrganisationProduct>();
    if (!includeDisabledP42Admin)
        pred.And(op => op.Enabled);
    if (!includeDisabledOrgAdmin)
        pred.And(op => op.AccessLevel == "NA" || op.AccessLevel == "NU");
    query = query.Where(pred);
}

However, the generated SQL is unchanged and the query returns the same number of rows.

I thought I might have had to do the Expand conversion as so:

query = query.AsExpandable().Where(pred);

But this causes a runtime error.

I think the issue is the fact that I am adding the predicate to a query that is already no longer a pure OrganisationProduct object, however I would like advise on how I insert my predicate at the right place.

Thanks and all :-)

Chris Walsh
  • 3,423
  • 2
  • 42
  • 62

1 Answers1

3

You have to assign the return value of And to the predicate:

pred = pred.And(op => op.Enabled);

Side note: you may like this predicate builder that works without Expand/AsExpandable, but has the same syntax.

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
  • Doh! Thanks! Amateur mistake. Each `pred` is presumably immutable then. – Chris Walsh Mar 10 '15 at 18:26
  • Thanks for the heads up on the universal PredicateBuilder. – Chris Walsh Mar 10 '15 at 18:29
  • Maybe I was a bit eager. Changing the `pred = pred.And` now causes a runtime error: `"The LINQ expression node type 'Invoke' is not supported in LINQ to Entities."` – Chris Walsh Mar 10 '15 at 18:33
  • That's what Expand or AsExpandable is for in Linqkit. But the other predicate builder works without it. – Gert Arnold Mar 10 '15 at 18:37
  • Thanks @Gert, but I included that first but that returned a different exception `Could not load type 'System.Data.Entity.Infrastructure.IDbAsyncEnumerable``1' from assembly 'EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.":"System.Data.Entity.Infrastructure.IDbAsyncEnumerable``1` – Chris Walsh Mar 10 '15 at 18:38
  • Looks like Linqkit's PB has some glitches with async, although I can't confirm that. Would you mind trying the other PB? – Gert Arnold Mar 10 '15 at 18:47
  • 2
    Wow! That worked! Still not sure why but I've checked the generated SQL and it is what I expected. Thumbs up to [Universal Predicate Builder](https://petemontgomery.wordpress.com/2011/02/10/a-universal-predicatebuilder/). – Chris Walsh Mar 11 '15 at 10:56