ORM tools made datacentric programs too easy to develop, but if it's been used without care, it will soon face a disaster in terms of SQL efficiency.
Microsoft proposes a tool for the developers who wants to know what is happening under the hood in EF.
It means, all SQL statements and information can be traced and logged in a file based on the developer's desire.
All you have to do is :
1. Install two wrappers for EntityFramework from Nuget.org
- CommunityEFProviderWrappers.EFProviderWrapperToolkit
- CommunityEFProviderWrappers.EFTracingProvider
2. Create a DbConnection object that is configured to log SQL staements like the one below and inject this object into DbContext.
var context = new DbContext(CreateTracingConnection(connectionString, "System.Data.SqlClient");
detail implementation of CreateTracingConnection is written below.
3. EnableTracing for data context.
((IObjectContextAdapter)this).ObjectContext.EnableTracing();
By this approach, you definitely know what commands are being executed when your application is running in debug mode.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static DbConnection CreateTracingConnection(string connectionStringName, string providerInvariantName) | |
{ | |
EFTracingProviderConfiguration.RegisterProvider(); | |
TraceEnabled = true; | |
var connstring = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString; | |
var connection = new EFTracingConnection | |
{ | |
ConnectionString = String.Format(@"wrappedProvider={0};{1}", providerInvariantName, connstring) | |
}; | |
connection.CommandFinished += (sender, e) => | |
{ | |
try | |
{ | |
Console.WriteLine(e.ToTraceString()); | |
} | |
catch | |
{ | |
// catch all exceptions so that we don't pass logging-related failures to user code | |
} | |
}; | |
return connection; | |
} | |
} |
No comments:
Post a Comment