dbContext找不到数据库 [英] DbContext cannot find database

查看:284
本文介绍了dbContext找不到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的应用程序的连接字符串在appsettings.json

The connection string for our app is set in appsettings.json

  "Data": {
"DefaultConnection": {
  "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=Customers;Trusted_Connection=True;MultipleActiveResultSets=true",

ConfigureServices中,我们有

            services.AddEntityFramework()
            .AddSqlServer()
            .AddDbContext<CustomersContext>(options =>
                options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

这似乎在这种情况下有效

This seems to work in cases like this

var membershipUser = await _userManager.FindByEmailAsync(email);

还有这个

var result = await _userManager.CreateAsync(newUser);

但是当我尝试这个时会摔倒

but falls over when I try this

            using (var customers = new CustomersContext())
        {
            var deviceList = customers.Devices.Where(d => d.UserId == membershipUser.Id);

错误是InvalidOperationException: No database providers are configured. Configure a database provider by overriding OnConfiguring in your DbContext class or in the AddDbContext method when setting up services.

如果我尝试这个

            public partial class CustomersContext : IdentityDbContext<ApplicationUser>
// note this inherits from IdentityDbContext<ApplicationUser> not DbContext
// refer http://stackoverflow.com/questions/19902756/asp-net-identity-dbcontext-confusion
{
    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        options.UseSqlServer(@"Server=(localdb)\\mssqllocaldb;Database=Customers;Trusted_Connection=True;MultipleActiveResultSets=true");
    }

我收到此错误

Local Database Runtime error occurred. Specified LocalDB instance name is invalid

为什么我的应用程序在某些情况下可以找到数据库,而在其他情况下却找不到?

Why is it my app can find the database in some cases but not others?

推荐答案

问题是,尽管您已使用DI服务配置了CustomerContext,如下所示:

The problem is that although you've configured a CustomerContext with the DI services as shown here:

services.AddEntityFramework()
        .AddSqlServer()
        .AddDbContext<CustomersContext>(options =>
           options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

您没有注入CustomerContext,而是像这样更新它:

You are not having the CustomerContext injected, instead you are newing it up like this:

using (var customers = new CustomersContext())
 {
...
}

使用不带参数的构造函数,因此您的CustomerContext没有像启动时那样配置,并且没有连接字符串.

using a constructor that takes no parameters, so your CustomersContext is not configured like the one in startup and it has no connection string.

由于您在AccountController中提到了它,因此您需要做的就是将CustomersContext添加到AccountController的构造函数中,以便在启动时配置的那个将被注入.像这样:

Since you mention you need it in the AccountController, then all you need to do is add CustomersContext to the constructor of AccountController, so that the one you configured in startup will get injected. Like this:

private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ISmsSender _smsSender;
private readonly ILogger _logger;
private CustomersContext _customerContext;

public AccountController(
    UserManager<ApplicationUser> userManager,
    SignInManager<ApplicationUser> signInManager,
    IEmailSender emailSender,
    ISmsSender smsSender,
    ILoggerFactory loggerFactory,
    CustomersContext customerContext)
{
    _userManager = userManager;
    _signInManager = signInManager;
    _emailSender = emailSender;
    _smsSender = smsSender;
    _logger = loggerFactory.CreateLogger<AccountController>();
    _customerContext = customerContext;
}

这样,您将获得正确配置的CusotmersContext,而不必自己进行更新.如果出于某种原因您确实想自己进行更新,则需要使用带有IServiceProvider和DbContextOptions的构造函数.因此,您将在AccountController的构造函数中接收这些对象,并在像这样新建CustomerContext时将它们传递给他们:

That way you get a properly configured CusotmersContext and you don't have to new it up yourself. If for some reason you did want to new it up yourself you need to do so using a constructor that takes IServiceProvider and DbContextOptions. So you would receive those objects in the constructor of AccountController and you would pass them in as you new up the CustomersContext like this:

using (var customers = new CustomersContext(serviceProvider, dbContextOptions))
 {
...
}

这篇关于dbContext找不到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆