简体   繁体   中英

Entity Framework Return Lazy Loading Query and Apply Filters in Another Method

I have a large base query that I'd like to add conditional Where filters on in various methods. I was hoping to use Lazy Loading to create the base query in a method and call it elsewhere in the various places I'm adding conditional where clauses and then execute at the end.

I tried something like:

public IEnumerable<MyModel> GetBaseQuery()
{

    IEnumerable<MyModel> base= context.MyTable1.Join(...{lot of joins here})
        .Select{
        ...select all of required fields for my model
        }
    return base;
}

public IEnumerable<MyModel> GetResultsByKeyword()
{
    IEnumerable<MyModel> model= GetBaseQuery();
    if(condition1 is true)
    {
        model = model.Where(x => x.Field1 == "Field1Value");
    }
    if(condition2 is true)
    {
        model = model.Where(x => x.Field2 == "Field2Value");
    }

    return model.Tolist(); //execute the query when calling ToList()
}

The above returns no results, but if I put everything into one big method, then it does what I want it to do. My actual design has probably 7 or so different methods that would call the 'base' query and I'm trying to avoid replicating the base query in each method for 1) readability and 2) ongoing maintenance if the query ever needs to be edited to add more fields.

The two comments point to the code's two problems. Using IEnumerable will run the query before the additional query predicates are evaluated, and they will be evaluated in memory. And secondly .Where doesn't mutate the IQueryable/IEnumerable, it returns a new IQueryable/IEnumerable.

So should be something like:

public IQueryable<MyModel> GetBaseQuery()
{

    var base = context.MyTable1. . . .
    return base;
}

public ICollection<MyModel> GetResultsByKeyword()
{
    IQueryable<MyModel> qry = GetBaseQuery();
    if (condition1 is true)
    {
        qry = qry.Where(x => x.Field1 == "Field1Value");
    }
    if (condition2 is true)
    {
        qry = qry.Where(x => x.Field2 == "Field2Value");
    }

    return qry.Tolist(); //execute the query when calling ToList()
}

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