2

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.

4

2 回答 2

2

ToList 和 ToArray 都枚举了导致执行查询的集合。AsEnumrable 完成了查询构建(即您不能再向查询添加位),但在枚举集合之前它不会实际执行。

在您的示例中,任何枚举您的集合的操作都将检索数据。例如一个foreach。

于 2012-09-23T19:38:38.413 回答
0

当上下文被释放时,您将不得不添加ToArray()ToList()防止对结果进行迭代。投射到 aList<T>将无济于事:这甚至是不可能的。

如果您之后可以迭代结果,您将冒着再次执行此操作的风险,这会引发异常。

于 2012-09-23T19:58:33.573 回答