我正在尝试将应用程序配置为使用我的类(派生自 DbContext
)ApplicationDbContext
连接到我的数据库。我已经做了配置文件appsetting.json
:
"Data": {
"SportStoreProducts": {
"ConnectionStrings":"Server=(localdb)\\MSSQLLocalDB;Database=SportStore;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
我使用依赖注入(inject)来传递实现
IConfiguration
的对象(即 appsetting.json
)通过启动构造:public class Startup
{
public Startup(IConfiguration configuration) => Configuration = configuration;
public IConfiguration Configuration { get; }
}
现在我想在
ConfigureServices
中使用这个配置文件Startup
的方法并使用扩展方法AddDbContext
注册我的ApplicationDbContext
使用我在配置文件中分配的 SQL 数据库 (SportStore
):public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(
options => options.UseSqlServer(***);
}
我的问题是我应该将什么传递给
UseSqlServer
方法作为参数(***),以便它可以使用我提供的配置属性将上下文连接到 SQL Server 数据库?
最佳答案
services.AddDbContext<BloggingContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("ConnectionStrings")));
有关详细信息,请参阅 -> link
关于c# - 如何配置 UseSqlServer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49840628/