Asp.Net 身份 2.0 : The entity type User is not part of the model for the current context

标签 asp.net entity-framework dependency-injection unity-container asp.net-identity

更新到最新的 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/

相关文章:

c# - dot net gridview排序问题

c# - OfType<> 与 "is"查询的性能

c# - 如何使用 StructureMap 将不同的混凝土绑定(bind)到属性

javascript - 在 Telerik RadGrid 中单击复选框打开对话框窗口

c# - 当 gridview 在页面加载时加载时默认加载第二页

c# - Entity Framework 应用了太多迁移

android - 如何将 Activity 和 Fragment 注入(inject) RecyclerAdapter (Dagger 2)

c# - 将参数从复合根向下传递到 DI 链

c# - 客户端验证,包括 unicode 字符范围

c# - 无法在mvc项目中以所需格式呈现数据