已配置关系存储,但未指定要使用的 DbConnection 或连接字符串
本文关键字:DbConnection 字符串 连接 关系 配置 存储 未指定 | 更新日期: 2023-09-27 18:35:33
当我想添加用户时 asp.net 我使用 vnext 和 ef7 出现此错误:
已配置关系存储,但未指定 要使用的数据库连接或连接字符串。
这是怎麽?
考虑我的应用启动:
using DomainModels;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Routing;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;
using Presentation.DataAccessLayer.Context;
using Microsoft.AspNet.Identity;
namespace Presentation
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
Configuration = new Configuration()
.AddJsonFile("config.json")
.AddEnvironmentVariables();
}
public IConfiguration Configuration { get; set; }
public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFramework().AddSqlServer().AddDbContext<ApplicationContext>();
services.AddDefaultIdentity<ApplicationContext, ApplicationUser, IdentityRole>(Configuration);
services.AddMvc();
}
public void Configure(IApplicationBuilder app)
{
app.UseStaticFiles();
app.UseIdentity();
app.UseMvc(
routes =>
{
routes.MapRoute("default", "{controller}/{action}/{id?}",
new {controller = "Home", action = "Index"});
});
}
}
}
这是我的config.json:
{
"Data": {
"DefaultConnection": {
"Connectionstring": "Data Source=.''sqlexpress;Initial Catalog=CraftCenter;Integrated Security=True;"
}
},
"EntityFramework": {
"ApplicationDbContext": {
"ConnectionStringKey": "Data:DefaultConnection:ConnectionString"
}
}
}
我认为问题是您的 DbContext 类名与配置中指定的名称不同。
例如,如果您有一个名为 MembershipDbContext
的 DbContext,则可以通过 EntityFramework
中的属性指定它应该使用的连接字符串。
{
"Data": {
"Membership": {
"ConnectionString": "Server=(localdb)''mssqllocaldb;Database=Membership;Trusted_Connection=True;MultipleActiveResultSets=true"
}
},
"EntityFramework": {
"MembershipDbContext": {
"ConnectionStringKey": "Data:Membership:ConnectionString"
}
}
这比在代码中指定连接字符串密钥更简洁。
在您的情况下,DbContext 名称是ApplicationContext
的,您在配置中指定的名称是不匹配的ApplicationDbContext
。
"EntityFramework": {
"MembershipDbContext": {
"ConnectionStringKey": "Data:Membership:ConnectionString"
}
}
将ConnectionStringKey
更改为ConnectionString
对我有用。
我更喜欢在安装程序类中配置存储:
public virtual void ConfigureServices(IServiceCollection services)
{
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<ApplicationContext>(options => options.UseSqlServer(
Configuration.Get("Data:DefaultConnection:ConnectionString")));
services.AddDefaultIdentity<ApplicationContext, ApplicationUser, IdentityRole>(Configuration);
services.AddMvc();
}
我明白了,并在我的上下文中添加了这段代码:
protected override void OnConfiguring(DbContextOptions options)
{
options.UseSqlServer(Startup.Configuration.Get("Data:DefaultConnection:ConnectionString"));
}
它在 DbContext 中查找连接字符串,因此您需要在 config.json 中将"ConnectionStringKey"更改为"ConnectionString"。