Core中实现DbContext连接字符串

Core中实现DbContext连接字符串

本文介绍了如何在.NET Core中实现DbContext连接字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的情况与此链接非常相​​似,或者至少我的代码相似,并且我试图找到一种在.NET Core语法中应用相同方法的方法。

My situation is quite similar to this link or at least my code is similar and I am trying to find a way to apply this same method in .NET Core syntax.

我的特定代码如下:

public partial class CompanyFormsContext : DbContext
{
    public CompanyFormsContext()
        : base("name=CompanyFormsContext")
    {
    }

    public CompanyFormsContext(string connName)
        : base("name=" + connName)
    {
    }
    ...
}

我收到一条错误消息:

o在 base( name = CompanyFormsContext) base( name = = connName)中的括号中。

when I go over the parenthesis in base("name=CompanyFormsContext") or base("name=" = connName).

在.NET Core中实现此功能的正确方法是什么?

What is the correct way of implementing this functionality in .NET Core?

编辑:

我想分享一下我在appsettings.json文件中具有以下数据库连接信息:(但是,启动时没有设置。 cs)

I wanted to share that I have the following information for database connection in my appsettings.json file: (However, I do not have settings in the startup.cs)

  "Data": {
    "CompanyFormsContext": {
      "ConnectionString": "Server=(localdb)\\projectsv13;Database=companyforms;Trusted_Connection=True;"
    },
    "CompanyFormsContextQA": {
      "ConnectionString": "Server=(localdb)\\projectsv13;Database=companyforms;Trusted_Connection=True;"
    }
  }

,我发现以下链接,并且我想知道一个简单的受保护的覆盖无效OnConfiguring(DbContextOptionsBuilder optionsBuilder)是否足以修复我的连接?

and I have found the following link Adding DbContextOptions in Startup.cs not registering data store in the website and I am wondering if a simple protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) will be enough to fix my connection or not?

从链接中:

services.AddEntityFramework(Configuration)
    .AddSqlServer()
    .AddDbContext<MyDbContext>(
        options =>
        options.UseSqlServer(Configuration.Get("Data:CompanyFormsContext:ConnectionString"))
    );

我在Startup.cs中需要这种服务吗?

Do I need this kind of a service in my Startup.cs?

推荐答案

另一种选择是调用采用DbContextOptions的基本构造函数:

Another option would be to call the base constructor that takes a DbContextOptions:

public BooksContext(string connectionString) : base(GetOptions(connectionString))
{
}

private static DbContextOptions GetOptions(string connectionString)
{
    return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connectionString).Options;
}

这篇关于如何在.NET Core中实现DbContext连接字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 00:41