문제

In the earlier versions of Entity Framework, we were able to reach the Context out of ObjectQuery in order to read Parameters, Connection, etc. as below:

var query = (ObjectQuery<T>)source;

cmd.Connection = (SqlConnection)((EntityConnection)query.Context.Connection).StoreConnection;
cmd.Parameters.AddRange(
    query.Parameters.Select(x => new SqlParameter(
        x.Name, x.Value ?? DBNull.Value)
    ).ToArray()
);

When I look at the DbSet<T> object, I am unable to find any equivalent of this. My purpose here is to create extensions which will manipulate the query and get the result out of it.

Here is an instance: http://philsversion.com/2011/09/07/async-entity-framework-queries

Or should I write the extension for DbContext class and work with Set method?

Any idea?

Edit

Here is what I did so far. Basic implementation so far but certainly not ready for production. Any suggestions on this?

public static async Task<IEnumerable<T>> QueryAsync<T>(this DbContext @this, System.Linq.Expressions.Expression<Func<T, bool>> predicate = null)
    where T : class {

        var query = (predicate != null) ? @this.Set<T>().Where(predicate) : @this.Set<T>();

        var cmd = new SqlCommand();

        cmd.Connection = (SqlConnection)(@this.Database.Connection);
        cmd.CommandText = query.ToString();

        if (cmd.Connection.State == System.Data.ConnectionState.Closed) { 

            cmd.Connection.ConnectionString = new SqlConnectionStringBuilder(cmd.Connection.ConnectionString) {
                AsynchronousProcessing = true
            }.ToString();

            cmd.Connection.Open();
        }

        cmd.Disposed += (o, e) => {

            cmd.Clone();
        };

        var source = ((IObjectContextAdapter)@this).ObjectContext.Translate<T>(
            await cmd.ExecuteReaderAsync()
        );

        return source;
}
도움이 되었습니까?

해결책

This is a nice workaround, although I don't think you can make it much more generally applicable than what you already have.

A few things to keep in mind:
- Depending on the EF query, e.g. if you are using Include or not, the columns returned in the reader might not match the properties in the type T you are passsing.
- Depending on whether you have inheritance in your model, the T that you pass to translate may not always be the right thing to materialize for every row returned.
- After the task returned by ExecuteReaderAsync completes, you still have to retrieve each row, which depending on the execution plan for the query and the latency you are getting with the server is potentially also a blocking operation.

Async support is not coming to EF in 5.0 but we worked with other teams to make sure we have all the necessary building blocks included in .NET 4.5 and the feature is pretty high in our priority list. I encourage you to vote for it in our UserVoice site.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top