'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync

.Net Core 1.0.0 - SDK Preview 2 (x64)

.Net Core 1.0.0 - VS "15" Preview 2 (x64)

.Net Core 1.0.0 - Runtime (x64)

So, we updated an RC1 app to the latest versions above. After many hours of switching references, it's running. However, when logging in (AccountController/Login), I am getting an error at:

public class AccountController : BaseController
{
public UserManager<ApplicationUser> UserManager { get; private set; }
public SignInManager<ApplicationUser> SignInManager { get; private set; }
private readonly IEmailSender EmailSender;


public AccountController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, IEmailSender emailSender)
{
UserManager = userManager;
SignInManager = signInManager;
EmailSender = emailSender;
}


// GET: /Account/Login
[HttpGet]
[AllowAnonymous]
public IActionResult Login(string returnUrl = null)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}


//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(ViewModels.Account.LoginViewModel model, string returnUrl = null)
{
if (ModelState.IsValid)
{
// Errs this next line
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, false); // <-- ERRS HERE '.PasswordSignInAsync'
if (result.Succeeded)
return RedirectToLocal(returnUrl);


ModelState.AddModelError("", "Invalid email or password.");
return View(model);
}


// If we got this far, something failed, redisplay form
return View(model);
}
            

It blows up with the following error message:

InvalidOperationException: No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.

Here is the Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));


// Add EF services to the services container.
services.AddEntityFrameworkSqlServer()
.AddDbContext<LogManagerContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:Connectionstring"]));


services.AddSingleton(c => Configuration);


// Add Identity services to the services container.
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<LogManagerContext>()
.AddDefaultTokenProviders();
            

        

// Add MVC services to the services container.
services.AddMvc();


services.AddTransient<IHttpContextAccessor, HttpContextAccessor>();


//Add all SignalR related services to IoC. - Signal R not ready yet - Chad
//services.AddSignalR();


//Add InMemoryCache
services.AddMemoryCache();


services.AddSession(options =>
{
options.IdleTimeout = System.TimeSpan.FromHours(1);
options.CookieName = ".LogManager";
});


// Uncomment the following line to add Web API servcies which makes it easier to port Web API 2 controllers.
// You need to add Microsoft.AspNet.Mvc.WebApiCompatShim package to project.json
// services.AddWebApiConventions();
// Register application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
        

}


// Configure is called after ConfigureServices is called.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseSession();


// Configure the HTTP request pipeline.
// Add the console logger.
//loggerFactory.MinimumLevel = LogLevel.Information; - moved to appsettings.json -chad
loggerFactory.AddConsole();
loggerFactory.AddDebug();


loggerFactory.AddNLog();


// Add the following to the request pipeline only in development environment.
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
//app.UseDatabaseErrorPage(DatabaseErrorPageOptions.ShowAll);
}
else
{
// Add Error handling middleware which catches all application specific errors and
// sends the request to the following path or controller action.
app.UseExceptionHandler("/Home/Error");
}


env.ConfigureNLog("NLog.config");


// Add static files to the request pipeline.
app.UseStaticFiles();


// Add cookie-based authentication to the request pipeline.
app.UseIdentity();


//SignalR
//app.UseSignalR();


// Add MVC to the request pipeline.
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index" }
);


// Uncomment the following line to add a route for porting Web API 2 controllers.
// routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
});
}

And here's the Context:

public class ApplicationUser : IdentityUser
{
// Add Custom Profile Fields
public string Name { get; set; }
}


public class LogManagerContext : IdentityDbContext<ApplicationUser>
{
public DbSet<LogEvent> LogEvents { get; set; }
public DbSet<Client> Clients { get; set; }
public DbSet<LogEventsHistory> LogEventsHistory { get; set; }
public DbSet<LogEventsLineHistory> LogEventsLineHistory { get; set; }
public DbSet<LogRallyHistory> LogRallyHistory { get; set; }
public DbSet<Flag> Flags { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{


builder.Entity<LogEvent>().HasKey(x => x.LogId);
builder.Entity<LogEvent>().ToTable("LogEvents");
builder.Entity<Client>().HasKey(x => x.ClientId);
builder.Entity<Client>().ToTable("Clients");
builder.Entity<LogEventsHistory>().HasKey(x => x.HistoryId);
builder.Entity<Flag>().HasKey(x => x.FlagId);
builder.Entity<Flag>().ToTable("Flags");
builder.Entity<LogRallyHistory>().HasKey(x => x.HistoryId);
builder.Entity<LogEventsLineHistory>().HasKey(x => x.LineHistoryId);


base.OnModelCreating(builder);
}
201741 次浏览

如果使用 AddDbContext,则还要确保 DbContext 类型 在其构造函数中接受 DbContextOptions 对象并将其传递给 DbContext 的基本构造函数。

The error message says your DbContext(LogManagerContext ) needs a constructor which accepts a DbContextOptions. But I couldn't find such a constructor in your DbContext. So adding the below constructor probably solves your problem.

public LogManagerContext(DbContextOptions options) : base(options)
{
}

编辑评论

如果没有显式注册 IHttpContextAccessor,请使用以下代码:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

我可以通过在 DbContextOptionsBuilder 中添加连接字符串来重写 MyContext 中的 Configuration 来解决这个问题:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var connectionString = configuration.GetConnectionString("DbCoreConnectionString");
optionsBuilder.UseSqlServer(connectionString);
}
}

如果无法识别 SetBasePathAddJsonFile方法,请安装这些包 :

  • 微软。扩展。配置。文件扩展
  • 微软。扩展。配置。 Json

这是我找到的解决办法。

文档/blob/master/实体-框架/核心/杂项/ https://github.com/aspnet/entityframework configuring-dbcontext.md

通过 AddDbContext 配置 DBContext

public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<BloggingContext>(options => options.UseSqlite("Data Source=blog.db"));
}

向 DBContext 类添加新的构造函数

public class BloggingContext : DbContext
{
public BloggingContext(DbContextOptions<BloggingContext> options)
:base(options)
{ }


public DbSet<Blog> Blogs { get; set; }
}

向控制器注入上下文

public class MyController
{
private readonly BloggingContext _context;


public MyController(BloggingContext context)
{
_context = context;
}


...
}

重写 DbContext 的构造函数 试试这个:-

public DataContext(DbContextOptions<DataContext> option):base(option) {}

我知道这已经过时了,但这个答案仍然适用于较新的 Core 版本。

如果您的 DbContext实现碰巧位于与启动项目不同的项目中,并且您运行的是 ef migrations,您将看到此错误,因为该命令将无法调用应用程序的启动代码,从而使您的数据库提供程序没有配置。要修复它,你必须让 ef migrations知道他们在哪里。

dotnet ef migrations add MyMigration [-p <relative path to DbContext project>, -s <relative path to startup project>]

-s-p都是 默认设置为当前文件夹的可选项。

除了已接受的答案外,如果任何人在正确地做了以下操作后仍然得到错误答案:

  • Startup.cs: services.AddDbContext<ApplicationDbContext>(options => ... )
  • In ApplicationDbContext.cs : public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options){}

Check that DbContext 类没有任何无参数的公共构造函数 (need to delete it if any). FYI, you might be added parameterless public constructor for some reason i.e. Scaffolding DbContext.

详情(我在我的网站上写的文章) : NET 核心故障排除

尽管有带 DbContextOptions 参数的构造函数,我还是出现了这个错误。当我将解决方案启动从一个项目更改为多个项目时,出现了错误。检查解决方案-> 右击-> 属性-> 公共属性-> 启动项目中是否有多个启动项目。

我只是弄错了凭证,典型的混乱错误信息。

在我的例子中,一个新的.NET6 Web API 中,Saffold-DbContext 命令添加了如下2个构造函数:

 public BookStoreDbContext()
{
}


public BookStoreDbContext(DbContextOptions<BookStoreDbContext> options)
: base(options)
{
}

只要移除第一个,应该就可以了。

大家好,我遇到了这个问题,我的情况有点不同 我尝试在 not asp. net 核心 web 应用程序中测试 AppDbContext 文件 因此没有依赖注入来处理添加特定提供程序(如 SQLServer)的步骤,所以我的解决方案是在 AppdbContext 文件中覆盖以下函数:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
private string conn = "Server=servername;Database=dbName;Trusted_Connection = True; MultipleActiveResultSets = true";
        

if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(conn);
}
}

如果您使用 asp dot net web 应用程序的实体框架核心,您应该在 ConfigureServices 函数的启动文件中添加这个配置,如下所示:

public void ConfigureServices(IServiceCollection services)
{
        

// name of your dbcontext file
services.AddDbContext<AppDbContext>(option =>
option.UseSqlServer(Configuration.GetConnectionString("AlternativeConnection")));
services.AddControllersWithViews();


}

如果您正在使用顶级语句 Program.cs,请确保 builder.Services.AddDbContext<>行在这一行之前声明:

var app = builder.Build();

我在使用 EF Core 6时遇到了这个问题:

  • 首先,我在上下文文件中添加了一个没有参数的构造函数

  • 第二,我在相同的上下文文件中重写了 OnConfiguration 方法,如下所示:

      protected override void OnConfiguring(DbContextOptionsBuilder options)
    => options.UseSqlServer("MyConnectionString");
    
  • 然后进行迁移

效果很好。