【发布时间】:2021-10-11 14:52:47
【问题描述】:
这行导致我的项目出错:
options.UseSqlServer(Configuration.GetConnectionString("SchoolContext")));
错误:
System.ArgumentNullException: '值不能为空。 (参数'connectionString')'
我已经在网上阅读了一堆类似的问题,但我找不到有效的更改。 UseSqlServer() 中的参数似乎返回 null。这让我相信我有一个配置错误。
这是我的启动文件和 json 文件的代码:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using ContosoUniversity.Data;
namespace ContosoUniversity
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddDbContext<SchoolContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("SchoolContext")));
services.AddDatabaseDeveloperPageExceptionFilter();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}
}
{
"ConnectionStrings": {
"DefaultConnection": "Server=(***;Database=***;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information",
"Microsoft.EntityFrameworkCore.Database.Command": "Information"
}
},
"AllowedHosts": "*"
}
感谢您提供任何帮助。谢谢。
【问题讨论】:
-
您的配置中似乎没有定义
SchoolContext连接,只有DefaultConnection -
您正在尝试获取一个名为
SchoolContext的连接字符串,但配置中只有一个名为DefaultConnection的连接字符串
标签: c#