Chris Patterson
Chris Patterson

Reputation: 591

asp.net Identity 2.0 How to change connection string / DbContext at runtime?

I would like to do the following in my MVC5, asp.net identity 2.0 app:

  1. Change the connection string used by the ApplicationDBContext at runtime. I will have numerous clients, each with their own SQL database. So at session start, I need to be able to specify the desired database connection.

  2. I assume to class ApplicationDbContext that I add the overload:

    public static ApplicationDbContext Create(string connectionString)
    {
        return new ApplicationDbContext(connectionString);
    }
    
  3. I also am assuming that in Startup.Auth.cs that I need to modify this line to pass in the connection string. If so, then I am having troubles here with doing just that.

    app.CreatePerOwinContext(ApplicationDbContext.Create);
    

Am I going down the right road? Am I missing anything else? I am basically stuck at this point. TIA for your help.

Upvotes: 3

Views: 2577

Answers (4)

Zeeshan
Zeeshan

Reputation: 131

It usually occurs when you are using external SQL server instead of visual studio's SQL express. All you have to do is follow below steps:

  1. Goto IdentityModels.cs .
  2. In class ApplicationDbContext constructor place you connection string in place of "DefaultConnString" (First parameter of constructor).
  3. Create a Empty DB in your server with name "ApplicationDbContext".
  4. Now Run your application.

It should resolve by this.

Upvotes: 0

LauranVC
LauranVC

Reputation: 1

This is just a fix to use the constructor for initializing the connection string. Just make a new contructor that takes you connectionstring, and fill it in the IdentityDbContext

 public class DbContext : IdentityDbContext<User>
{
    public DbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {

    }

    public DbContext(string ConnectionString) : base(ConnectionString)
    {

    }
}

Upvotes: 0

Terri
Terri

Reputation: 352

Same question.

I have

public ApplicationDbContext() : base(@"data source=.\SQLEXPRESS; initial catalog=mydata; integrated security=true")

and several other options that give me the same result. The 'hard coded' connection works just fine. But I need to set initial catalog={somevariable} such that I can get {somevariable} either from the user or from AspNetUser for the user who is logging in.

A code example would be really helpful. "Just do this" isn't so much.

Upvotes: 0

Hao Kung
Hao Kung

Reputation: 28200

You can just change ApplicationDbContext to create an ApplicationDbContext instance with the proper connection string. The Create is basically an ApplicationDbContext factory method.

Upvotes: 1

Related Questions