当我想添加用户时,我使用asp.net vnext和ef7我收到此错误:
已配置关系存储,但未指定 要使用的DbConnection或连接字符串。
这是什么?
考虑我的应用开始:
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"
}
}
}
答案 0 :(得分:4)
"EntityFramework": {
"MembershipDbContext": {
"ConnectionStringKey": "Data:Membership:ConnectionString"
}
}
将ConnectionStringKey
更改为ConnectionString
对我有用。
答案 1 :(得分:3)
我认为问题是您的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
且不匹配。
答案 2 :(得分:2)
我更喜欢在Setup类中配置商店:
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();
}
答案 3 :(得分:1)
我得到它并在我的上下文中添加此代码:
protected override void OnConfiguring(DbContextOptions options)
{
options.UseSqlServer(Startup.Configuration.Get("Data:DefaultConnection:ConnectionString"));
}
答案 4 :(得分:1)
它在DbContext中寻找连接字符串,因此您需要更改&#34; ConnectionStringKey&#34;到&#34; ConnectionString&#34;在config.json中。