Is it possible to configure/pass connection string to the DbContext
in the constructor?
public partial class MyContext : DbContext
{
public MyContext() { }
public MyContext(DbContextOptions<MyContext> options) : base(options) { }
}
MyContext opt = new MyContext("con_str");
rather than hard coding it in:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(
@"Server=(localdb)\mssqllocaldb;Database=MyDB;Integrated Security=True");
}
How do I use:
DbContextOptions<MyContext> opts;
The following answer: Pass connection string to code-first DbContext does not work.
services.AddDbContext<YourDbContext>(options =>
{
options.UseSqlServer(Configuration.GetSection("YourConn").Value);
options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
});
"YourConn": "yourconnectionstring"
public partial class MyContext : DbContext
{
private string _conn = "";
public MyContext(string conn)
{
_conn = conn;
}
public MyContext(DbContextOptions<MyContext> options) : base(options) { }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(_conn);
}
}
Then you can use
MyContext opt = new MyContext("con_str");