c# - 如何配置 UseSqlServer?

标签 c# asp.net-mvc configuration dbcontext

我正在尝试将应用程序配置为使用我的类(派生自 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/

相关文章:

c# 通过outlook 2013发送html电子邮件

c# - 如何将运费从购物车发送到paypal

asp.net - 在 ASP.NET MVC 中将集合传递给 EditorFor

javascript - 在鼠标悬停在禁用的下拉菜单上时显示工具提示

c# - System.Web.HttpContext.Current.User.Identity.IsAuthenticated 返回 false

c# - 什么是 session Cookie?

c# - 如何在出现错误时优雅地退出我的应用程序?

java - 从 log4j1 迁移到 log4j2

symfony - 使用 Symfony2 的配置类时,允许配置数组中存在额外的未定义选项

configuration - 如何在 Wildfly 的standalone.xml 配置文件中引用环境变量?