如何在.NET Core中实现DbContext连接字符串?

时间:2021-10-22 02:14:24

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.

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

Pass connection string to code-first DbContext

将连接字符串传递给代码优先的DbContext

My specific code is as follows:

我的具体代码如下:

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

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

I get an error saying:

我收到一个错误说:

Error CS1503 Argument 1: cannot convert from 'string' to 'Microsoft.EntityFrameworkCore.DbContextOptions' CompanyForms..NETCoreApp,Version=v1.0

错误CS1503参数1:无法从'string'转换为'Microsoft.EntityFrameworkCore.DbContextOptions'CompanyForms..NETCoreApp,Version = v1.0

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

当我查看base(“name = CompanyFormsContext”)或base(“name =”= connName)中的括号时。

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

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

Edit:

编辑:

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)

我想分享我在appsettings.json文件中有关于数据库连接的以下信息:(但是,我在startup.cs中没有设置)

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

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?

我发现以下链接在Startup.cs中添加DbContextOptions没有在网站上注册数据存储,我想知道一个简单的受保护覆盖​​void OnConfiguring(DbContextOptionsBuilder optionsBuilder)是否足以修复我的连接?

From the link:

从链接:

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

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

我的Startup.cs中是否需要这种服务?

3 个解决方案

#1


7  

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

另一个选择是调用带有DbContextOptions的基础构造函数:

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

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

#2


10  

Generally you are going to want to read it from config at start-up, and then use the connection string to configure an Entity Framework DbContext service for your process.

通常,您希望在启动时从config读取它,然后使用连接字符串为您的进程配置Entity Framework DbContext服务。

1) Add a line to your appsettings.json:

1)在appsettings.json中添加一行:

"DbConnectionString": "Server=s;Database=db;Trusted_Connection=True;",

2) Read the line in you Startup.cs class (after the Startup method is called to build the Configuration - so usually in the ConfigureServices method) like this:

2)读取Startup.cs类中的行(在调用Startup方法构建配置之后 - 通常在ConfigureServices方法中),如下所示:

var connection = Configuration["DbConnectionString"];

3) If using Entity Framework add a database context service (MyDbContext is the context class generated by EF). You also want to tell the built-in dependency injection how to instantiate your database context:

3)如果使用Entity Framework添加数据库上下文服务(MyDbContext是由EF生成的上下文类)。您还想告诉内置依赖项注入如何实例化您的数据库上下文:

services.AddDbContext<MyDbContext>(options => options.UseSqlServer(connection));
services.AddScoped<IMyDbContext, MyDbContext>();

Where IMyDbContext is (at it's simplist) just an interface you've extracted from your MyDbContext

IMyDbContext(简称)只是你从MyDbContext中提取的一个接口

4) Now you can define your controller to take a MyDbContext and the DI will take care of building it and passing it in when the controller is invoked:

4)现在你可以定义你的控制器来获取MyDbContext,DI将负责构建它并在调用控制器时传入它:

public MyController(IMyDbContext context)
{
    _context = context  // store for later use
}

#3


2  

IMO best practice:

IMO最佳实践:

add to your configuration.json:

添加到您的configuration.json:

     "ConnectionStrings": {
    "BooksContext": "Server=MyServer;Database=MyDb;Trusted_Connection=True;"
  }

and to initialize section:

并初始化部分:

services.AddDbContext<BooksContext>(options => options.UseSqlServer(configuration.GetConnectionString(nameof(BooksContext))));

#1


7  

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

另一个选择是调用带有DbContextOptions的基础构造函数:

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

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

#2


10  

Generally you are going to want to read it from config at start-up, and then use the connection string to configure an Entity Framework DbContext service for your process.

通常,您希望在启动时从config读取它,然后使用连接字符串为您的进程配置Entity Framework DbContext服务。

1) Add a line to your appsettings.json:

1)在appsettings.json中添加一行:

"DbConnectionString": "Server=s;Database=db;Trusted_Connection=True;",

2) Read the line in you Startup.cs class (after the Startup method is called to build the Configuration - so usually in the ConfigureServices method) like this:

2)读取Startup.cs类中的行(在调用Startup方法构建配置之后 - 通常在ConfigureServices方法中),如下所示:

var connection = Configuration["DbConnectionString"];

3) If using Entity Framework add a database context service (MyDbContext is the context class generated by EF). You also want to tell the built-in dependency injection how to instantiate your database context:

3)如果使用Entity Framework添加数据库上下文服务(MyDbContext是由EF生成的上下文类)。您还想告诉内置依赖项注入如何实例化您的数据库上下文:

services.AddDbContext<MyDbContext>(options => options.UseSqlServer(connection));
services.AddScoped<IMyDbContext, MyDbContext>();

Where IMyDbContext is (at it's simplist) just an interface you've extracted from your MyDbContext

IMyDbContext(简称)只是你从MyDbContext中提取的一个接口

4) Now you can define your controller to take a MyDbContext and the DI will take care of building it and passing it in when the controller is invoked:

4)现在你可以定义你的控制器来获取MyDbContext,DI将负责构建它并在调用控制器时传入它:

public MyController(IMyDbContext context)
{
    _context = context  // store for later use
}

#3


2  

IMO best practice:

IMO最佳实践:

add to your configuration.json:

添加到您的configuration.json:

     "ConnectionStrings": {
    "BooksContext": "Server=MyServer;Database=MyDb;Trusted_Connection=True;"
  }

and to initialize section:

并初始化部分:

services.AddDbContext<BooksContext>(options => options.UseSqlServer(configuration.GetConnectionString(nameof(BooksContext))));