如何配置UseSqlServer?

Moh*_*sen 3 c# asp.net-mvc configuration dbcontext

我正在尝试将应用程序配置为使用我的类(派生自DbContextApplicationDbContext连接到我的数据库。我已经制作了配置文件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 数据库?

Ira*_*nia 8

 services.AddDbContext<BloggingContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("ConnectionStrings")));
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请参阅 ->链接


小智 6

抱歉,可能有些晚了,但是:

  1. 安装包 Microsoft.EntityFrameworkCore.SqlServer
  2. 添加参考: using Microsoft.EntityFrameworkCore;


小智 6

对于 .NET 6.0 只需执行以下操作:

builder.Services.AddDbContext<cursosContext>(options => options.UseSqlServer("name=ConnectionStrings:NombreCadena"));
Run Code Online (Sandbox Code Playgroud)

  • 通过额外的支持信息可以改进您的答案。请[编辑]添加更多详细信息,例如引文或文档,以便其他人可以确认您的答案是正确的。您可以[在帮助中心](/help/how-to-answer)找到有关如何写出好的答案的更多信息。 (3认同)