DbContext 找不到数据库

DbContext cannot find database

我们应用程序的连接字符串在 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"]));

这似乎适用于这种情况

var membershipUser = await _userManager.FindByEmailAsync(email);

还有这个

var result = await _userManager.CreateAsync(newUser);

但是当我尝试这个的时候摔倒了

            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 
{
    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

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

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

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

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

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

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

既然你在 AccountController 中提到你需要它,那么你需要做的就是将 CustomersContext 添加到 AccountController 的构造函数中,这样你在启动时配置的就会被注入。像这样:

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 的构造函数中接收这些对象,并在新建 CustomersContext 时将它们传入,如下所示:

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