小编Bal*_*ler的帖子

在 EF 上下文中使用 appsettings.json 配置

我应该指出我是 .NET 的新手......

我有以下 appsettings.json 文件:

{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    },
    "ConnectionStrings": {
        "MyContext": "Host=localhost;Database=test;Username=user;Password=''"
    }
}
Run Code Online (Sandbox Code Playgroud)

在 MyContext.cs 文件中,我想从 appsettings.json 配置读取连接字符串:

using Microsoft.EntityFrameworkCore;
using System;
using System.Configuration;

namespace My.Models
{
  public partial class MyContext : DbContext
  {

  protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  {
    Console.WriteLine(ConfigurationManager.ConnectionStrings.Count);
    if (!optionsBuilder.IsConfigured)
    {
  optionsBuilder.UseNpgsql(ConfigurationManager.ConnectionStrings["MyContext"].ConnectionString);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

ConfigurationManager.ConnectionStrings["MyContext"].ConnectionString为空,有什么想法吗?

我在 Startup.cs via 中成功使用了配置文件Configuration.GetConnectionString("MyContext"),但在这里我想从该配置中读取 ASP.NET 应用程序之外的情况的连接字符串(即在我想要执行的 EF 迁移中using var db = new MyContext();),但我不知道为什么上面返回 …

c# asp.net entity-framework-core .net-core

5
推荐指数
1
解决办法
4751
查看次数

标签 统计

.net-core ×1

asp.net ×1

c# ×1

entity-framework-core ×1