C# 如何配置UseSqlServer?
我正在尝试将应用程序配置为使用我的类(派生自C# 如何配置UseSqlServer?,c#,asp.net-mvc,configuration,dbcontext,C#,Asp.net Mvc,Configuration,Dbcontext,我正在尝试将应用程序配置为使用我的类(派生自DbContext)ApplicationDbContext连接到我的数据库。我已经创建了配置文件appsetting.json: "Data": { "SportStoreProducts": { "ConnectionStrings":"Server=(localdb)\\MSSQLLocalDB;Database=SportStore;Trusted_Connection=True;MultipleActiveResult
DbContext
)ApplicationDbContext
连接到我的数据库。我已经创建了配置文件appsetting.json
:
"Data": {
"SportStoreProducts": {
"ConnectionStrings":"Server=(localdb)\\MSSQLLocalDB;Database=SportStore;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
我使用依赖项注入通过启动构造传递实现IConfiguration
(即appsetting.json
)的对象:
public class Startup
{
public Startup(IConfiguration configuration) => Configuration = configuration;
public IConfiguration Configuration { get; }
}
现在,我想在ConfigureServices
启动方法中使用此配置文件,并使用扩展方法AddDbContext
注册我的ApplicationDbContext
以使用配置文件中分配的SQL数据库(SportStore
):
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(
options => options.UseSqlServer(***);
}
public void配置服务(IServiceCollection服务)
{
services.AddDbContext(
options=>options.UseSqlServer(***);
}
我的问题是,我应该向UseSqlServer
方法传递什么作为参数(***),以便它可以使用我提供的配置属性将上下文连接到SQL Server数据库?services.AddDbContext(options=>
services.AddDbContext<BloggingContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("ConnectionStrings")));
options.UseSqlServer(Configuration.GetConnectionString(“ConnectionString”));
有关更多详细信息,请参见->抱歉,可能有些晚了,但是: