我在.NET Core控制台应用程序中使用Entity Framework Core。我将连接字符串存储在App.config
文件中,并在上下文类中使用ConfigurationManager
来访问连接字符串。
当我想向项目中添加新的迁移时,出现以下错误:
System.NullReferenceException: Object reference not set to an instance of an object.
at EF_tut.Context.OnConfiguring(DbContextOptionsBuilder optionsBuilder) in C:\..\Context.cs:line 12
at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
at Microsoft.EntityFrameworkCore.Internal.InternalAccessorExtensions.GetService[TService](IInfrastructure1 accessor)
1 factory) at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType) at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.b__0() at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(FuncObject reference not set to an instance of an object.
这是我的
App.config
文件:<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="EfTutDb"
connectionString="Data Source=.;Initial Catalog=EF_tut;Integrated Security=True;"/>
</connectionStrings>
</configuration>
这是我的上下文类:
class Context : DbContext
{
public DbSet<Student> Students { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings["EfTutDb"].ConnectionString); // Line 12.
}
}
当我尝试在main方法中使用
ConfigurationManger
获取连接字符串时,我得到了连接字符串,但是当我添加迁移时,我得到了Null Reference错误。
最佳答案
也许这是一种解决方法,但是它可以工作:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var configuration = new ConfigurationBuilder()
.SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
.AddXmlFile("App.config")
.Build();
optionsBuilder.UseSqlServer(configuration.GetValue<string>("connectionStrings:add:EfTutDb:connectionString"));
}
}
关于c# - 添加迁移时用于提取数据库连接字符串时,ConfigurationManager返回null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55659207/