如何将连接字符串传递给 Entity Framework Core 中的 DBContext?
How do I pass connection string to DBContext in Entity Framework Core?
是否可以configure/pass连接字符串到构造函数中的DbContext
?
public partial class MyContext : DbContext
{
public MyContext() { }
public MyContext(DbContextOptions<MyContext> options) : base(options) { }
}
MyContext opt = new MyContext("con_str");
而不是硬编码:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(
@"Server=(localdb)\mssqllocaldb;Database=MyDB;Integrated Security=True");
}
如何使用:
DbContextOptions<MyContext> opts;
以下答案:Pass connection string to code-first DbContext 无效。
Startup.cs
services.AddDbContext<YourDbContext>(options =>
{
options.UseSqlServer(Configuration.GetSection("YourConn").Value);
options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
});
appsettings.json
"YourConn": "yourconnectionstring"
已编辑
YourDbContext.cs
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);
}
}
那你就可以使用
MyContext opt = new MyContext("con_str");
是否可以configure/pass连接字符串到构造函数中的DbContext
?
public partial class MyContext : DbContext
{
public MyContext() { }
public MyContext(DbContextOptions<MyContext> options) : base(options) { }
}
MyContext opt = new MyContext("con_str");
而不是硬编码:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(
@"Server=(localdb)\mssqllocaldb;Database=MyDB;Integrated Security=True");
}
如何使用:
DbContextOptions<MyContext> opts;
以下答案:Pass connection string to code-first DbContext 无效。
Startup.cs
services.AddDbContext<YourDbContext>(options =>
{
options.UseSqlServer(Configuration.GetSection("YourConn").Value);
options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
});
appsettings.json
"YourConn": "yourconnectionstring"
已编辑
YourDbContext.cs
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);
}
}
那你就可以使用
MyContext opt = new MyContext("con_str");