免责声明:我正在尝试了解有关 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"
}
}