实体类型ApplicationRole不是当前上下文的模型的一部分

本文关键字:上下文 模型 一部分 类型 ApplicationRole 实体 | 更新日期: 2023-09-27 18:23:38

我正在尝试将autofac集成到我的WCF服务中。我对Identity框架有问题。我无法添加任何用户或角色,因为有一个例外:实体类型[Name]不是当前上下文模型的一部分。我在Global.asax中注册了如下类型:

var builder = new ContainerBuilder();
builder.RegisterType<Service1>().SingleInstance();
builder.Register(c => new ApplicationContext(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString)).As<IdentityDbContext<ApplicationUser>>().AsSelf().SingleInstance();
builder.RegisterType<ClientManager>().As<IClientManager>();
builder.RegisterType<IdentityUnitOfWork>().As<IUnitOfWork>();
builder.RegisterType<ApplicationUserManager>().As<UserManager<ApplicationUser>>();
builder.RegisterType<UserStore<ApplicationUser>>().As<IUserStore<ApplicationUser>>();
builder.RegisterType<ApplicationRoleManager>().As<RoleManager<ApplicationRole>>();
builder.RegisterType<RoleStore<ApplicationRole>>().As<IRoleStore<ApplicationRole, string>>();
AutofacHostFactory.Container = builder.Build();

然后我解析我的UnitOfWork类:

var a = AutofacHostFactory.Container.Resolve<IUnitOfWork>();
var role = new ApplicationRole { Name = "admin" };
a.RoleManager.Create(role);

在最后一行之后,我得到了解释。我的"当前上下文"有什么问题?

实体类型ApplicationRole不是当前上下文的模型的一部分

问题是我试图用创建的AplicationContext将角色添加到不同的dbContext中。我刚刚做了这个:

builder.RegisterType<ApplicationUserManager>().As<UserManager<ApplicationUser>>(); builder.Register(c => new UserStore<ApplicationUser>(c.Resolve<IdentityDbContext<ApplicationUser>>())) .As<IUserStore<ApplicationUser>>() .InstancePerLifetimeScope(); builder.RegisterType<ApplicationRoleManager>().As<RoleManager<ApplicationRole>>(); builder.Register(c => new RoleStore<ApplicationRole>(c.Resolve<IdentityDbContext<ApplicationUser>>())) .As<IRoleStore<ApplicationRole, string>>() .InstancePerLifetimeScope();

相关文章: