17
votes

My Scenario:

I'm using EF7 for standard CRUD operations and Dapper for more complex queries that require increase in speed. From startup.cs I'm injecting my DbContext into my DAL which does then obviously does the database queries. Dapper requires a connection string. I want to inject my EF7 DbContext connection string into the Dapper query.

My Question:

How do I get the connection string from the DbContext like before: DbContext.Database.Connection?

It changed from Database to DatabaseFacade type in EF7, and with that, DbConnection Connection was also removed.

Surely there should be some persistent connection string in the DbContext that I can query?

My Research:

The method I'm using at the moment is, and it works:

public partial class CustomContext : DbContext
{
    public readonly string _connectionString;

    public CustomContext (DbContextOptions options)
        : base(options)
    {
            _connectionString = ((SqlServerOptionsExtension)options.Extensions.First()).ConnectionString;
    }
}

I know its still in beta, but am I missing something?

Thanks for your time.

2
FYI i'm using beta7 of EF7. - Nick De Beer
Side note: you should consider using the .FromSql(query) and .AsNoTracking() methods to improve EF's query speed so you don't need Dapper + EF in one project. - natemcmaster
You lead me right. This works for me.ctor: public DbContext(DbContextOptions<DbContext> options) : base(options) { this.Database = new DatabaseFacade(this); } - Johan

2 Answers

13
votes

I've searched EF7 sources and it seems that you are correct with your current approach.

Connection string is stored in SqlServerOptionsExtension. When you call UseSqlServer(connectionString) the code is as follows (extracted only interesting lines):

var extension = options.FindExtension<SqlServerOptionsExtension>()
extension.ConnectionString = connectionString;

I'm not sure why connection string was removed from obvious place, but it may be that devs abstracted away connection string to allow us to use non-standard databases (like in-memory database etc.).

This looks much clearer IMO:

Configuration.Get("Data:ConnectionString")
7
votes

If you have a fully materialized context, you can also use this:

 var conn = context.Database.GetDbConnection();
 ConnectionString = conn?.ConnectionString;
 conn?.Dispose();