user1662812
user1662812

Reputation: 2601

Immediate execution with EF

I have this code that executes a Stored Procedure mapped via EF EDM.

meTest<MCTEntities, ObjectResult<retrieveMedia_Result>>(u => u.retrieveMedia(campaign_id: 1), ConnectionResolver.MCT_DB_Connection);

The method:

public static TValue meTest<U, TValue>(Func<U, TValue> func, String connection)
            where U : ObjectContext, new()
        {
            using (U entitiesContext = (U)Activator.CreateInstance(typeof(U), new[] { connection }))
            {
                return func(entitiesContext);
            }
    }

The issue is that retrieveMedia returns ObjectResult<retrieveMedia_Result> and this is done with deferred execution that results in error: Calling 'Read' when the data reader is closed is not a valid operation.

Now, I know that I can call ToList() or ToArray(), but is there any other way to force immediate execution?

I am not sure that casting ObjectResult<retrieveMedia_Result> to List<retrieveMedia_Result> is the right thing to do.

Upvotes: 2

Views: 522

Answers (2)

Gert Arnold
Gert Arnold

Reputation: 109205

You will have to add ToArray() or ToList() to prevent iterating over the results when the contexts has been disposed. Casting to a List<T> will not help: it's not even possible.

If you could iterate over the result afterwards you would run the risk of doing that more that once, which throws an exception.

Upvotes: 0

undefined
undefined

Reputation: 34299

ToList and ToArray both enumerate the collection which is what causes the query to be executed..AsEnumrable completes the query build (ie you can no longer add bits to the query) but its not actually executed until the collection is enumerated.

In your example any action which enumerates your set will retrieve the data. For example a foreach.

Upvotes: 2

Related Questions