NetCore 6.0 如何访问dbContext文件中的连接字符串

NetCore 6.0 How to access connection string in dbContext file

免责声明:我正在努力学习net 6.0,我是菜鸟

这是我正在尝试做的事情:

这是我所做的:

这个上下文文件的大部分是自动生成的,我唯一做的就是更新 public TransparencyContext(IConfiguration config) 以包含 Iconfig,这样我就可以在 optionsBuilder.UseSqlServer(config.GetConnectionString("SQLDB"));

中访问它

TransparencyContext.cs

  namespace EFTutorial.Models
{
    public partial class TransparencyContext : DbContext
{
    private readonly IConfiguration config;

    public TransparencyContext()
    {
    }
    public TransparencyContext(IConfiguration config)
    {
        this.config = config;
    }

    public TransparencyContext(DbContextOptions<TransparencyContext> options)
        : base(options)
    {
    }

    public virtual DbSet<Fundraiser> Fundraisers { get; set; } = null!;
    public virtual DbSet<Person> Persons { get; set; } = null!;

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

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Fundraiser>(entity =>
        {
            entity.Property(e => e.Description).IsUnicode(false);

            entity.Property(e => e.EndDate).HasColumnType("datetime");

            entity.Property(e => e.Goal).HasColumnType("decimal(18, 2)");

            entity.Property(e => e.Name)
                .HasMaxLength(1000)
                .IsUnicode(false);
        });

        modelBuilder.Entity<Person>(entity =>
        {
            entity.Property(e => e.DateOfBirth).HasColumnType("datetime");

            entity.Property(e => e.FirstName)
                .HasMaxLength(100)
                .IsUnicode(false);

            entity.Property(e => e.LastName)
                .HasMaxLength(100)
                .IsUnicode(false);
        });

        OnModelCreatingPartial(modelBuilder);
    }

    partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
}

然后我尝试通过这样做从家庭控制器对其进行测试。

private TransparencyContext _transparencyContext;
        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
            _transparencyContext = new();
        }
public IActionResult Index()
        {
            var p = new Person();
            p.FirstName = "Entity";
            p.LastName = "Framework";

            _transparencyContext.Persons.Add(p);
            _transparencyContext.SaveChanges();
            return View();
        }

当我这样做时,我得到配置变量(在 TransparencyContext 中)为空(System.ArgumentNullException: 'Value cannot be null(Parameter 'connectionString')').我没有更改我的 program.cs,这是创建项目时的方式。

Program.cs

 var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

我知道可以从 app.Configuration 访问配置文件,但不确定如何让 TransparencyContext.cs 可以访问配置,这样我就可以获得 db.I 的连接字符串 已经尝试寻找在 Microsoft 文档中,但他们没有展示他们如何使 Iconfiguration 可用,并且只展示他们使用 it.Any 非常感谢帮助。

我在想我可能需要将服务注册到配置但不确定如何操作。

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "SQLDB": "Server=AzureConnectionStringCopyPaste"
  }
}
  1. 默认配置文件名是appsettings.json(不是AppSettings.Json)

  2. 您应该在主机构建器中配置您的配置。 示例:

     var configuration = new ConfigurationBuilder()
                                 .AddJsonFile("appsettings.json", false, true)
                                 .AddEnvironmentVariables()
                                 .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", true, true)
                                 .Build();
    
    builder.UseConfiguration(configuration)
    
  3. 您也可以使用 WebBuilder 方法 .ConfigureAppConfiguration 来配置正在使用 AppConfiguration

对当前设置的快速修复只是将 IConfiguration 注入控制器并使用它来构建上下文:

public HomeController(ILogger<HomeController> logger, IConfiguration cfg)
{
    _logger = logger;
    _transparencyContext = new(cfg);
}

但是“正确”和惯用的方法是使用 DI 来 register and resolve 上下文:

  1. 删除除TransparencyContext(DbContextOptions<TransparencyContext> options)
  2. 之外的所有构造函数
  3. 使用 AddDbContextAddDbContextFactory:
  4. 在 DI 中注册上下文
builder.Services.AddDbContextFactory<TransparencyContext>(opts =>
 opts.UseSqlServer(builder.Configuration.GetConnectionString("SQLDB")));
  1. 在控制器中解析
public HomeController(ILogger<HomeController> logger, TransparencyContext ctx)
{
    _logger = logger;
    _transparencyContext = ctx;
}