gpt4 book ai didi

c# - .Net Core 2 EF core 连接串问题

转载 作者:行者123 更新时间:2023-12-03 21:22:10 26 4
gpt4 key购买 nike

这是我的 appsettings.json

 "ConnectionStrings": {
"Circolari": "Server=abcde;Database=Circolari;Trusted_Connection=True;"
}

这是我的startup.cs
 public Startup(IConfiguration configuration, IHostingEnvironment env)
{
Configuration = configuration;
IConfigurationBuilder configurationBuilder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = configurationBuilder.Build();
}


// This method gets called by the runtime. Use this method to add services to the container.

public void ConfigureServices(IServiceCollection services)
{
//Circolari
string connectoionString = Configuration.GetConnectionString("Circolari");
services.AddDbContext<CircolariContext>(options => options.UseSqlServer(connectoionString));
services.AddMvc();
}

所以当我做查询时
using (CircolariContext db = new CircolariContext(new DbContextOptions<CircolariContext>()))
{
List<Argomenti> listaArgomenti = db.Argomenti.ToList();
}

我有问题:处理请求时发生未处理的异常。

InvalidOperationException: 使用了命名的连接字符串,但在应用程序的配置中找不到名称“Circolari”。请注意,仅在使用“IConfiguration”和服务提供程序时才支持命名连接字符串,例如在典型的 ASP.NET Core 应用程序中。见 https://go.microsoft.com/fwlink/?linkid=850912想要查询更多的信息。

Microsoft.EntityFrameworkCore.Storage.Internal.NamedConnectionStringResolverBase.ResolveConnectionString(string connectionString)

有人可以帮我吗?

最佳答案

YouContextFile.cs 添加此代码

 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
// add IConfigurationRoot to get connection string
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
.AddJsonFile("appsettings.json")
.Build();
optionsBuilder.UseSqlServer(configuration.GetConnectionString("DefaultConnection"), x => x.UseNetTopologySuite());
}
}

关于c# - .Net Core 2 EF core 连接串问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52659818/

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