c# - IRelationalDatabaseCreator 服务

标签 c# entity-framework asp.net-core asp.net-core-mvc entity-framework-core

昨天我开始学习 ASP.NET 5 MVC 6 with Entity Framework 7.0.0-rc1-final 并按照本教程进行操作:Link 。问题是当我运行它时,它会在此函数上抛出 NullPointerException:

 if (serviceProvider.GetService<IRelationalDatabaseCreator>().Exists())
        {//adding some entities }

我的连接字符串是:"Server=(localdb)\\MSSQLLocalDB; Database=Test; Trusted_Connection=True; MultipleActiveResultSets=true"

在 Startup.cs 中我有以下代码:

public void ConfigureServices(IServiceCollection services)
 {
      services.AddEntityFramework()
              .AddSqlServer()
              .AddDbContext<Models.HRPContext>(options =>
              {
                  options.UseSqlServer(Configuration["Data:ConnectionString"]);
              });
      ....... 
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
      Utils.AddSampleData.Initialize(app.ApplicationServices);
      ......
}

数据库 Test 尚未创建。有人解决了这个异常吗?谢谢

最佳答案

该教程是 out of date 。使用this one相反。

在更新的教程中,if 语句不存在。相反,它通过检查上下文对象的 Database 属性来检查数据库是否存在:

if (context.Database == null)
{
    throw new Exception("DB is null");
}

关于c# - IRelationalDatabaseCreator 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34675016/

相关文章:

c# - 如何将嵌入资源 JSON 文件添加到 ConfigurationBuilder 而不创建临时文件?

c# - Blazor 组件 : notify of collection-changed event causing thread collisions

javascript - 是否可以防止直接打开弹出窗口而不是通过 Javascript 打开?

c# - 同时将对象添加到具有属性的列表中

.net - 错误 175 : The specified store provider cannot be found in the configuration, 或无效

c# - 继承中的逆变

entity-framework - 在 Windows Azure 上将 SQL Server CE 4.0 与 Entity Framework 结合使用

c# - DateTime 在使用 Refit 序列化并用作 url 参数时失去精度

c# - 存储网络服务的密码?

c# - 如何将匿名 json 作为类成员并将所有转换为 c# 中的 json