免責宣告:我正在嘗試了解有關 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();
}
When i do this i get the config variable( in TransparencyContext) being null (System.ArgumentNullException: 'Value cannot be null(Parameter 'connectionString')'). I havent changed my program.cs and is the way it was when the project was created.
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();
I know that configuration file can be accessed from app.Configuration but not sure how to make configuration accessible for the TransparencyContext.cs so i can get the connection string for db.I have tried looking at Microsoft documents but they don't show how they make the Iconfiguration avaiable and only show them using it.Any help is much appreciated.
I am thinking I might need to register a service to configuration but not sure how to do it.
appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"SQLDB": "Server=AzureConnectionStringCopyPaste"
}
}
uj5u.com熱心網友回復:
對您當前設定的快速修復將只是注入IConfiguration控制器并使用它來構建背景關系:
public HomeController(ILogger<HomeController> logger, IConfiguration cfg)
{
_logger = logger;
_transparencyContext = new(cfg);
}
但是“正確”和慣用的方式是使用 DI 來注冊和決議背景關系:
- 洗掉所有建構式,除了
TransparencyContext(DbContextOptions<TransparencyContext> options) - 在 DI 中使用
AddDbContextor注冊背景關系AddDbContextFactory:
builder.Services.AddDbContextFactory<TransparencyContext>(opts =>
opts.UseSqlServer(builder.Configuration.GetConnectionString("SQLDB")));
- 在控制器中決議
public HomeController(ILogger<HomeController> logger, TransparencyContext ctx)
{
_logger = logger;
_transparencyContext = ctx;
}
uj5u.com熱心網友回復:
默認組態檔名為 appsettings.json(不是 AppSettings.Json)
您應該在主機構建器中配置您的配置。例子:
var configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json", false, true) .AddEnvironmentVariables() .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", true, true) .Build(); builder.UseConfiguration(configuration)您也可以使用
WebBuilder方法.ConfigureAppConfiguration來配置是使用 AppConfiguration
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/407845.html
標籤:
