Visualizzazione post con etichetta entity framework. Mostra tutti i post
Visualizzazione post con etichetta entity framework. Mostra tutti i post

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

giovedì 17 novembre 2011

Trace T-SQL statements generated by Entity Framework

If we want to keep track of a query with Entity Framework without use a profiler, we can use the method ToTraceString which is part of the ObjectQuery object. In practice, this method displays the commands sent from our T-SQL query to the database.

First, when using the ToTraceString method we need an open connection to the database, otherwise we will raise an exception.

Its use is very simple. Here an example:
using (MyEntities ctx= new MyEntities()) {
  var strSql = "SELECT VALUE t FROM MyEntities.Employees AS t";
  var myQuery = ctx.CreateQuery(strSql);
 
  ctx.Connection.Open();
 
  Console.WriteLine(myQuery.ToTraceString());
  Console.ReadLine();
}


The output will be something like:
SELECT
[it].[FirstName] AS [FirstName],
[it].[LastName] AS [LastName],
[it].[Age] AS [Age]
FROM [dbo].[Employees] AS [it]

One important thing about ToTraceString method is that it doesn’t execute the query but it's only output the statement to be executed.