Pass connection string to code-first DbContext
A little late to the game here, but another option is:
public class NerdDinners : DbContext
{
public NerdDinners(string connString)
{
this.Database.Connection.ConnectionString = connString;
}
public DbSet<Dinner> Dinners { get; set; }
}
After reading the docs, I have to pass the name of the connection string instead:
var db = new NerdDinners("NerdDinnerDb");
Thought I'd add this bit for people who come looking for "How to pass a connection string to a DbContext": You can construct a connection string for your underlying datastore and pass the entire connection string to the constructor of your type derived from DbContext.
(Re-using Code from @Lol Coder) Model & Context
public class Dinner
{
public int DinnerId { get; set; }
public string Title { get; set; }
}
public class NerdDinners : DbContext
{
public NerdDinners(string connString)
: base(connString)
{
}
public DbSet<Dinner> Dinners { get; set; }
}
Then, say you construct a Sql Connection string using the SqlConnectioStringBuilder like so:
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(GetConnectionString());
Where the GetConnectionString method constructs the appropriate connection string and the SqlConnectionStringBuilder ensures the connection string is syntactically correct; you may then instantiate your db conetxt like so:
var myContext = new NerdDinners(builder.ToString());