Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send connection string to ApplicationDBContext

I have customized the ApplicationDBContext class to receive a connection string via its constructor. It can connect to the database OK when called directly however when called through the app.CreatePerOwnContext I am unable to call it. My class definition is below:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(string databaseConnection)
        : base(databaseConnection, throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create(string databaseConnection)
    {
        return new ApplicationDbContext(databaseConnection);
    }
}

The problem is when it is called by Startup.Auth.cs in the following line.

app.CreatePerOwinContext(ApplicationDbContext.Create);

The create method also takes a connection string but the following does not work

app.CreatePerOwinContext(ApplicationDbContext.Create(connectionString));

It produces the following error:

Error   1   The type arguments for method 'Owin.AppBuilderExtensions.CreatePerOwinContext<T>(Owin.IAppBuilder, System.Func<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

What is the correct syntax to send a connection string to the ApplicationDbContext class so that the Owin context can reference it?

The connection string is correct but for completeness the code which sets it is below.

string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
like image 588
Three Value Logic Avatar asked Apr 23 '15 21:04

Three Value Logic


1 Answers

Please have a look at the declaration of the method you are using:

public static IAppBuilder CreatePerOwinContext<T>(
    this IAppBuilder app,
    Func<T> createCallback) where T : class, IDisposable

It is expecting an argument of the type Func<T>.

So you need to change your code to:

app.CreatePerOwinContext(() => ApplicationDbContext.Create(connectionString));
like image 189
Alex Avatar answered Oct 10 '22 04:10

Alex