【问题标题】:Pass connection string to .Net Core EF library from another library将连接字符串从另一个库传递到 .Net Core EF 库
【发布时间】:2020-02-19 19:46:21
【问题描述】:

我有一个 ASP.NET Core 应用程序,它分为三层,即:

  • 数据访问层(实体框架)
  • 业务逻辑层
  • ASP.NET MVC Web 应用程序

就像现在一样,配置工作正常,我可以访问我的 Web 应用程序库中的数据库。但是,当我首先使用 EF Db 构建数据访问层时,我得到了一个泛型类,它看起来像这样:

public partial class ClassContext: DbContext
{
    public ClassContext(DbContextOptions<ClassContext> options)
        : base(options)
    {
    }

    public virtual DbSet<Entity> Entity{ get; set; }
    ....

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer("ConnString");
        }
    }
}

如您所见,连接字符串被硬编码到我的OnConfiguring 方法中,不推荐这样做。

因此,我遵循了以下“指南”here,它建议我使用内置 DI,从我的 Web 库中传递连接字符串。

这是我做的:

public void ConfigureServices(IServiceCollection services)
{
    //Add connectionstring to EF
    services.AddDbContext<ClassContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnectionStringFromAppSettings")));
}

根据“指南”,应将连接字符串提供给我的ClassContext 类的构造函数 - 确实如此,但没有任何连接字符串..

这意味着,optionsBuilder.IsConfigured 评估为 false,并且想要使用硬编码的连接字符串。

因此,我非常想知道,如果我使用了不正确的 DI,因为我无法访问我的 ClassContext 类中的连接字符串

更新

我删除了OnConfiguring() 方法,现在将上下文注入到业务逻辑层中的服务类构造函数中:

public MasterService(ClassContext context)
{
    MinorService = new MinorService(context);
}

public Stuff AddStuffIntoDatabase(Stuff test)
{
    //business logic going before here
   MinorService.addstuffMethod(test) 
}

但是,当我想在我的数据库中执行操作时,现在出现以下错误:

没有为此 DbContext 配置数据库提供程序。可以通过覆盖 DbContext.OnConfiguring 方法或在应用程序服务提供者上使用 AddDbContext 来配置提供者。

这在之前没有发生过,当时我在 OnConfiguring() 方法中错误地配置了连接字符串。

【问题讨论】:

  • 您不必在 OnConfiguring 方法中再次添加连接字符串。该方法在配置 DbContext 之前 被调用。这就是它评估为假的原因。只需在 ConfigureServices 中添加连接字符串就足够了。调用 OnConfiguring 时,DbContextOptionsBuilder 已经配置为使用 sql server。
  • 感谢您的回答,我刚刚更新了我的问题 :-)
  • 也许这会对你有所帮助:stackoverflow.com/a/57980799/3883866

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


【解决方案1】:

appsettings.json 呢?是这样的吗?

"ConnectionStrings": {
    "ConnectionStringFromAppSettings": "your_connection_string"
  }

Configuration.GetConnectionString 始终搜索“ConnectionStrings”部分

https://docs.microsoft.com/it-it/dotnet/api/microsoft.extensions.configuration.configurationextensions.getconnectionstring?view=dotnet-plat-ext-3.1

【讨论】:

  • 您用于连接字符串的 json 块是否与答案中的完全匹配?
  • 是的。它是一个 mssql 服务器,所以我有以下内容:"Data source=IP_ADDRESS; Initial catalog=DB; User UD = ID; Password=PW"
猜你喜欢
  • 2021-11-18
  • 1970-01-01
  • 1970-01-01
  • 2018-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多