Moh*_*sen 3 c# asp.net-mvc configuration dbcontext
我正在尝试将应用程序配置为使用我的类(派生自DbContext
)ApplicationDbContext
连接到我的数据库。我已经制作了配置文件appsetting.json
:
"Data": {
"SportStoreProducts": {
"ConnectionStrings":"Server=(localdb)\\MSSQLLocalDB;Database=SportStore;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
Run Code Online (Sandbox Code Playgroud)
我使用依赖注入通过 Startup 构造传递对象实现IConfiguration
(即appsetting.json
):
public class Startup
{
public Startup(IConfiguration configuration) => Configuration = configuration;
public IConfiguration Configuration { get; }
}
Run Code Online (Sandbox Code Playgroud)
现在我想在ConfigureServices
方法中使用这个配置文件Startup
并使用扩展方法AddDbContext
来注册我ApplicationDbContext
使用SportStore
我在配置文件中分配的SQL数据库():
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(
options => options.UseSqlServer(***);
}
Run Code Online (Sandbox Code Playgroud)
我的问题是我应该将什么UseSqlServer
作为参数 (***)传递给方法,以便它可以使用我提供的配置属性将上下文连接到 SQL Server 数据库?
services.AddDbContext<BloggingContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("ConnectionStrings")));
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请参阅 ->链接
小智 6
抱歉,可能有些晚了,但是:
小智 6
对于 .NET 6.0 只需执行以下操作:
builder.Services.AddDbContext<cursosContext>(options => options.UseSqlServer("name=ConnectionStrings:NombreCadena"));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8770 次 |
最近记录: |