-
Notifications
You must be signed in to change notification settings - Fork 23
4. How to enable DB profiling?
Teddy edited this page Nov 3, 2015
·
1 revision
To enable DB profiling, you need to wrap your code for DB operations with the ProfiledDbConnection, ProfiledDbCommand, etc, classes provided by NanoProfiler.Data.
For most cases, you only need to wrap your IDbConnection instances with the ProfiledDbConnection class. For example, if you have a data layer DB operation below:
public class DemoDBDataService : IDemoDBDataService
{
public List<DemoData> LoadActiveDemoData()
{
using (ProfilingSession.Current.Step("Data.LoadActiveDemoData"))
{
using (var conn = GetConnection())
{
conn.Open();
using (var cmd = conn.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select Id, Name from [Table] where IsActive = @IsActive";
cmd.Parameters.Add(new SqlParameter("@IsActive", 1));
using (var reader = cmd.ExecuteReader())
{
var results = new List<DemoData>();
while (reader.Read())
{
results.Add(new DemoData { Id = reader.GetInt32(0), Name = reader.GetString(1) });
}
return results;
}
}
}
}
}
private IDbConnection GetConnection()
{
var conn = new SqlConnection(@"Server=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\DemoDB.mdf;Database=DemoDB;Trusted_Connection=Yes;");
return conn;
}
}
Your code of GetConnection() method need to be changed to as below:
public class DemoDBDataService : IDemoDBDataService
{
//...
private IDbConnection GetConnection()
{
var conn = new SqlConnection(@"Server=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\DemoDB.mdf;Database=DemoDB;Trusted_Connection=Yes;");
if (ProfilingSession.Current == null)
{
return conn;
}
var dbProfiler = new DbProfiler(ProfilingSession.Current.Profiler);
return new ProfiledDbConnection(conn, dbProfiler);
}
}