更新到最新的 Asp.Net Identity(从 1.0 到 2.0)后,我在数据库中的用户 CRUD 上遇到了一个异常:
实体类型 User 不是当前上下文模型的一部分
// for example here:
var manager = Container.Resolve<UserManager<User>>();
IdentityResult result = manager.Create(user, "Test passwd");
public class User : IdentityUser
{
// Some properties
}
public class AppDbContext : IdentityDbContext<User>
{
static AppDbContext()
{
// Without this line, EF6 will break.
Type type = typeof (SqlProviderServices);
}
public AppDbContext()
: this("DBName")
{
}
public AppDbContext(string connectionString)
: base(connectionString)
{
}
...
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Entity<User>()
.HasMany(c => c.SkippedTopics)
.WithMany(i => i.Users)
.Map(t =>
t.MapLeftKey("User_Id")
.MapRightKey("Topic_Id")
.ToTable("UserSkippedTopics"));
...
}
在更新之前,代码工作正常。有什么想法吗?
更新
问题出在 UserManager 类型的 Unity 配置中。
修复:我创建了空的 AppUserStore: UserStore 并将其注册为 IUserStore:
public class AppUserStore : UserStore<User>
{
public AppUserStore(AppDbContext context) : base(context)
{
}
}
...
public static void RegisterTypes(IUnityContainer container)
{
...
_container.RegisterType<AppDbContext, AppDbContext>(new InjectionConstructor());
_container.RegisterType<IUserStore<User>, AppUserStore>();
}
最佳答案
某处不应该有 UserStore
吗?我的意思是看起来你正在为我从未使用过的 DI 使用 Unity
所以我不知道它是如何工作的但通常要实例化 UserManager
你会做这样的事情:
var manager = new UserManager<User>(new UserStore<User>(new AppDbContext()));
关于Asp.Net 身份 2.0 : The entity type User is not part of the model for the current context,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22793102/