2

免责声明:我正在尝试了解有关 net 6.0 的更多信息,并且是新手。

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

  • 我正在尝试访问 TransparencyContext 中的 IConfiguration 文件,但我不断收到配置为空错误:System.ArgumentNullException:'值不能为空。(参数'connectionString')'。

这是我所做的:

  • 更新了 dbContext 的构造函数以注入IConfiguration 配置

这个 Context 文件的大部分是自动生成的,我唯一做的就是更新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,并且是创建项目时的方式。

程序.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 的连接字符串。我尝试查看 Microsoft 文档,但它们没有显示它们如何制作 Iconfiguration可用并且只向他们展示使用它。非常感谢任何帮助。

我想我可能需要注册一个服务来配置,但不知道该怎么做。

应用设置.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "SQLDB": "Server=AzureConnectionStringCopyPaste"
  }
}
4

2 回答 2

1
  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

于 2022-01-07T23:27:14.573 回答
1

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

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

但是“正确”和惯用的方式是使用 DI 来注册和解析上下文:

  1. 删除所有构造函数,除了TransparencyContext(DbContextOptions<TransparencyContext> options)
  2. 在 DI 中使用AddDbContextor注册上下文AddDbContextFactory
builder.Services.AddDbContextFactory<TransparencyContext>(opts =>
 opts.UseSqlServer(builder.Configuration.GetConnectionString("SQLDB")));
  1. 在控制器中解析
public HomeController(ILogger<HomeController> logger, TransparencyContext ctx)
{
    _logger = logger;
    _transparencyContext = ctx;
}
于 2022-01-07T23:57:23.417 回答