C# AddDBContext值上的Startup.cs错误不能为null
我正在尝试使用实体框架使与数据库的连接在.NETCore中工作。模型和上下文是通过DB-first方法构建的 在我的启动中,我有以下代码行:C# AddDBContext值上的Startup.cs错误不能为null,c#,.net-core,entity-framework-core,C#,.net Core,Entity Framework Core,我正在尝试使用实体框架使与数据库的连接在.NETCore中工作。模型和上下文是通过DB-first方法构建的 在我的启动中,我有以下代码行: // This method gets called by the runtime. ////Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbCo
// This method gets called by the runtime.
////Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<PersonalProfileContext>(options => options
.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc();
}
在我的背景下,我有以下几点:
public virtual DbSet<Companies> Companies { get; set; }
public virtual DbSet<Qualifications> Qualifications { get; set; }
public virtual DbSet<Roles> Roles { get; set; }
public virtual DbSet<RolesCompanies> RolesCompanies { get; set; }
public virtual DbSet<RolesUsers> RolesUsers { get; set; }
public virtual DbSet<Users> Users { get; set; }
public PersonalProfileContext(DbContextOptions<PersonalProfileContext> options)
: base(options)
{
return;
}
{
"DefaultConnection": {
"ConnectionString": "" <-- Not included for safety reasons
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"ApplicationInsights": {
"InstrumentationKey": "" <-- Not included for security reasons
}
}
在startup.cs中,我得到一个错误,在AddDBContext行中,值不能为null
在my appsettings.json文件中,它如下所示:
public virtual DbSet<Companies> Companies { get; set; }
public virtual DbSet<Qualifications> Qualifications { get; set; }
public virtual DbSet<Roles> Roles { get; set; }
public virtual DbSet<RolesCompanies> RolesCompanies { get; set; }
public virtual DbSet<RolesUsers> RolesUsers { get; set; }
public virtual DbSet<Users> Users { get; set; }
public PersonalProfileContext(DbContextOptions<PersonalProfileContext> options)
: base(options)
{
return;
}
{
"DefaultConnection": {
"ConnectionString": "" <-- Not included for safety reasons
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"ApplicationInsights": {
"InstrumentationKey": "" <-- Not included for security reasons
}
}
有人知道如何解决这个问题吗?这里的问题是appsettings.json的连接字符串部分不太正确 以下是您提供的内容:
"DefaultConnection": {
"ConnectionString": "" <-- Not included for safety reasons
}
返回null,这意味着:
options
.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
返回null,这意味着null被传递到对AddDbContext的调用中
这是一个容易犯的错误,也不容易发现。我的直接想法是Configuration.GetConnectionStringDefaultConnection是否返回正确的值?我的假设是连接字符串的值要么返回null,要么返回空,或者指向一个不存在的数据库。@JamieTaylor它确实返回null,但我不确定为什么当我在AppSettings.json文件中有DefaultConnection时,您的问题是没有从AppSettings.json文件访问连接字符串。是否可以共享它的编辑版本?@JamieTaylor请查看对我的问题的编辑:它的格式不好,但这正是您的目标:ConnectionString:{DefaultConnection:}
options
.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));