如何在.NET Core中实现DbContext连接字符串? [英] How can I implement DbContext Connection String in .NET Core?

查看:625
本文介绍了如何在.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.

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

我的特定代码如下:

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

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

我收到一条错误消息:


错误CS1503参数1:无法从字符串'到'Microsoft.EntityFrameworkCore.DbContextOptions'CompanyForms..NETCoreApp,Version = v1.0

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

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;"
    }
  }

,我发现以下链接在Startup.cs中添加DbContextOptions而不在网站中注册数据存储,并且我想知道一个简单的受保护的覆盖无效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连接字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆