Linq to Entities' dynamic where clause

dynamic entity-framework linq where-clause

Question

linq to entities is what I'm using (EF). My constructor accepts four string arguments. I have to generate the linq query based on which parameter is not null. I can use if-else clauses, but I also have another constructor with ten arguments, so there will be a lot of different combinations to test.

Example:

Constructor(p1,p2,p3,p4)
{
  var prod= from p in ctxt.products.expand("items\details")
            where p.x==p1 && p.xx==p2 && p.xxx==p3 && p.xxxx==p4
            select p;
}

Only if the argument is not null should there be condition tests in the where clause mentioned above. Specifically, the where clause should be as follows if p2 is null:

where p.x==p1 && p.xxx==p3 && p.xxxx==p4

Upon p2 and p3 becoming null,

where p.x==p1 && p.xxxx==p4

Can someone please advise me on how to proceed? If at all feasible, could you provide some example code?

1
10
2/3/2012 12:45:38 AM

Accepted Answer

DeferredExecution in Linq to the rescue. The execution of a Linq query depends on the request for data.

var prod = from p in ctxt.products.expand("items\details")
        select p;

if (p1 != null)
{
    prod = prod.Where(p => p.x == p1);
}

if (p2 != null)
{
    prod = prod.Where(p => p.xx == p2);
}

// Execute the query

var prodResult = prod.ToList();
11
2/3/2012 12:48:09 AM

Popular Answer

There's always the option to compose the query piecemeal and benefit from delayed query execution:

public Constructor(int? p1, int? p2, int? p3, int? p4)
{
    var prod = ctxt.products.expand("items\details");

    if(p1 != null)
        prod = prod.Where(p.x == p1);

    if(p2 != null)
        prod = prod.Where(p.xx == p2);

    if(p3 != null)
        prod = prod.Where(p.xxx == p3);

    if(p4 != null)
        prod = prod.Where(p.xxxx == p4);
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow