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

时间:2016-08-10 15:48:08

标签: c# asp.net .net entity-framework

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

Pass connection string to code-first DbContext

我的具体代码如下:

/usr/src/node_modules

我收到错误说:

  

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

当我在public partial class CompanyFormsContext : DbContext { public CompanyFormsContext() : base("name=CompanyFormsContext") { } public CompanyFormsContext(string connName) : base("name=" + connName) { } ... } base("name=CompanyFormsContext")中查看括号时。

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

修改

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

base("name=" = connName)

我在网站上找到了以下链接Adding DbContextOptions in Startup.cs not registering data store,我想知道一个简单的 "Data": { "CompanyFormsContext": { "ConnectionString": "Server=(localdb)\\projectsv13;Database=companyforms;Trusted_Connection=True;" }, "CompanyFormsContextQA": { "ConnectionString": "Server=(localdb)\\projectsv13;Database=companyforms;Trusted_Connection=True;" } } 是否足以修复我的连接?

从链接:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)

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

6 个答案:

答案 0 :(得分:23)

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

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

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

答案 1 :(得分:14)

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

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

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

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

var connection = Configuration["DbConnectionString"];

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

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

IMyDbContext(简言之)只是你从MyDbContext中提取的界面

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

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

答案 2 :(得分:4)

IMO最佳实践:

添加到 configuration.json

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

初始化部分:

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

答案 3 :(得分:1)

一个简单的方法是,使用 optionbuilder 来获取上下文:

    public static MyDbContext GetMyDbContext(string databaseName)
    {
        var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();

        optionsBuilder.UseSqlServer($@"Data Source=.\SqlExpress;Initial Catalog={databaseName};Integrated Security=True");

        return new MyDbContext(optionsBuilder.Options);

    }

答案 4 :(得分:0)

用于静态连接的Startup.cs

services.AddScoped<MyContext>(_ => new MyContext(Configuration.GetConnectionString("myDB")));

Table1Repository.cs用于动态连接

using (var _context = new MyContext(@"server=....){
context.Table1....
}

MyContext.cs

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

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

答案 5 :(得分:-1)

因此,我到处搜索了解决我的问题的解决方案,该解决方案是我需要根据需要进行连接的数据才能动态连接到数据库的动态解决方案。基本上是动态上下文。我没有在URL上传递数据,也没有简短的数据库列表。因此,这是我对提出的问题的解决方案。此代码将允许您使用appsettings.json文件定义带有占位符的连接字符串,该占位符将在运行时由该代码替换。您可以在控制器或其他您认为合适的类中完成此操作。

我同时使用静态上下文和动态上下文,但是您只能使用动态上下文。

希望有人会偶然发现这一点,并说声谢天谢地……虽然可能就像有人说的那样,这个家伙是个白痴。无论哪种方式,享受。

using System;
using System.Globalization;
using System.Linq;
using Microsoft.Extensions.Configuration;

namespace CallCenter.Repositories
{
    public class TestRepository : ITestRepository 
    {
        private readonly InsuranceContext _context;
        public TestRepository InsuranceContext context)
        {
            _context = context;
        }

        public void Add(string passedInStringWhichTellsWhatDatabaseToUse)
        {
            var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");

            var configuration = builder.Build();
            var connectionString = configuration.GetConnectionString("DefaultConnection");


                var agencyContext = new AgencyContext(connectionString.Replace("Database=replacethisstring", "Database=" + passedInStringWhichTellsWhatDatabaseToUse));

                var company = agencyContext.Companys.FirstOrDefault(x => x.ColumnNameInDb == "xyz");
                if (company != null)
                {
                    companyId = company.CompanyId.ToString();
                }

... your other code here which could include the using the passed in _context from the injected code (or you could not have any context passed in and just use dynamic context
            }

        }
    }
}

//The AgencyContext class would look like this:

using Microsoft.EntityFrameworkCore;

namespace CallCenter.Entities
{
    public class AgencyContext : DbContext
    {
        public AgencyContext(string connectionString) : base(GetOptions(connectionString))
        {

        }

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

        public DbSet<Companys> Companys { get; set; }
    }
}

//The startup.c IServiceProvider module has this:

        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddOptions();

            services.AddDbContext<InsuranceContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), b => b.UseRowNumberForPaging()));
            services.AddScoped<ITestRepository , TestRepository >();
....
}

最后,appsettings.jason文件将包含以下内容:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=yourservername;Database=replacethisstring;User ID=youruserid;Password=yourpassword;TrustServerCertificate=True;Trusted_Connection=False;Connection Timeout=30;Integrated Security=False;Persist Security Info=False;Encrypt=True;MultipleActiveResultSets=True;",
}
}
相关问题