entity-frameworkentity-framework-6entity-framework-plus

Entity Framework Plus - FutureValue() in a foreach loop


Recently I started using EF+ on our project with great success however sometimes I run into an issue that I have a set of entities for which I need to run a separate query.

So if I have a set of 20 customers I need to run 20 queries separately. I wonder if there is way how to avoid this using EF+ FutureValue() somehow in a foreach loop.

See this sample code:

foreach (var customer in customers)
                {
                    customer.SomeValue = ctx.SomeDatabaseTable.Where(myCondition).FutureValue();
                    // this would run 20 times ... any way how to run all of the 20 queries at once?
                }

Solution

  • You need first to generate all "QueryFuture" queries then you can use them.

    So two loop should make it works.

    var futureQueries = new List<BaseQueryFuture>();
    
    // create all query futures
    for(int i = 0; i < customers.Length; i++)
    {
        futureQueries.Add(ctx.SomeDatabaseTable.Where(myCondition).FutureValue());
    }
    
    // assign result (the first solved will make the call to the DB)
    for(int i = 0; i < customers.Length; i++)
    {
         customer.SomeValue = ((QueryFutureValue<SomeValueType>)futureQueries[i]).Value;
    }