gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 04:38:21 24 4
gpt4 key购买 nike

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

这是我正在尝试做的:

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

这是我所做的:

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

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

透明上下文.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);
}
}

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

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"
}
}

最佳答案

快速修复当前设置的方法是注入(inject) IConfiguration进入 Controller 并使用它来构建上下文:

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

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

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

关于c# - NetCore 6.0 如何访问dbContext文件中的连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70628152/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com