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.
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.