Three Value Logic
Three Value Logic

Reputation: 1112

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;

Upvotes: 7

Views: 4729

Answers (1)

Alex
Alex

Reputation: 13234

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));

Upvotes: 14

Related Questions