7

My DbContext ctor looks like this:

public class FnordDbContext : DbContext
{
    public FnordDbContext() : base("Fnord")
    {
    }

    /* stuff */
}

And my mvc-mini-profiler bootstrapper looks like this:

var sqlConnectionFactory = new SqlConnectionFactory(ConfigurationManager.ConnectionStrings["Fnord"].ConnectionString);
var profiledConnectionFactory = new MvcMiniProfiler.Data.ProfiledDbConnectionFactory(sqlConnectionFactory);
Database.DefaultConnectionFactory = profiledConnectionFactory;

If I remove the connection string in my DbContext ctor, I get profiling as expected. But I don't want to have to name my connection string according to EF's convention. What do I need to change to make mvc-mini-profiler work with my DbContext use?

half-ogre
  • 594
  • 3
  • 7

1 Answers1

6

You can pass in the a ProfiledDbConnection explicitly to the ctor of your DbContext:

public class MyDbContext : DbContext {
    public MyDbContext()
        : base(GetProfiledConnection()) {
    }

    private static DbConnection GetProfiledConnection() {
        var connectionString = ConfigurationManager.ConnectionStrings["name"].ConnectionString;
        var connection = new SqlConnection(connectionString);
        return ProfiledDbConnection.Get(connection);
    }
}
davidfowl
  • 37,120
  • 7
  • 93
  • 103
  • 3
    At first this didn't work for me. I was getting the error "Invalid object name 'dbo.EdmMetadata'" for all querues. Because I'm using migrations, there is no EdmMetadata. To fix this, I had to add: modelBuilder.Conventions.Remove(); to my OnModelCreating. I guess I'll still mark this as an answer. :P – half-ogre Aug 12 '11 at 08:58
  • 4
    Using the latest versions of EF and MiniProfiler I had to do this: public MyDbContext() : base(GetProfiledConnection(), true){ } private static DbConnection GetProfiledConnection() { var connectionString = ConfigurationManager.ConnectionStrings["name"].ConnectionString; var connection = new SqlConnection(connectionString); return new ProfiledDbConnection(connection, MiniProfiler.Current); } – Peter Mourfield Jul 02 '12 at 14:34