lunedì 16 gennaio 2012

EntityDataSource and isolation level.

Suppose we have a asp.net page and display some data from a database table in a GridView. The latter is connected to EntityDataSource.
If we are running a long elaboration on that table (as an update or other processing), the page containing the data to show cannot hang and display our data until processing is finished.
That's not ever that we want....

Probably this behavior is not what we want. How can we solve it?

Using EntityDataSource ContextCreated event we can "attach" a transaction to the ObjectContext used by datasource.

protected void MyEntityDataSource_ContextCreated(object sender, EntityDataSourceContextCreatedEventArgs e) {
        e.Context.Connection.Open();
        e.Context.Connection.BeginTransaction(IsolationLevel.ReadUncommitted);
}

First we have to manually open the database connection. Then, start a database transaction specifying the isolation level we want to use. In this case, we need "ReadUncommitted" so we can read all data from database, including those not yet committed (dirty).