Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

After updating to latest Asp.Net Identity (from 1.0 to 2.0) i got an exception on CRUD of a user from DB:

The entity type User is not part of the model for the current context

// 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"));
    ...
}

Before the update the code worked correctly. Any ideas?


UPDATE

The problem was in Unity configuration for UserManager types.

Fix: i created empty AppUserStore: UserStore and registered it as 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>();
}
like image 481
Jan Lobau Avatar asked Jan 27 '26 14:01

Jan Lobau


1 Answers

shouldn't there be UserStore somewhere? I mean looks like you're using Unity for DI which I've never used so I don't know how it works but normally to instantiate UserManager you do something like this:

var manager = new UserManager<User>(new UserStore<User>(new AppDbContext()));
like image 159
dima Avatar answered Jan 29 '26 04:01

dima



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!