2

I am attempting to get away from code-first migrations.

The problem is that AspNetUsers is extending IdentityUser. As a result, when I try to use a DbContext then I get the following errors.

  • EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType.
  • EntityType 'IdentityUserRole' has no key defined. Define the key for this EntityType.

I want to use AspNetUsers for two purposes:

  1. Identity management.
  2. Querying users from the database.

Is it possible to go this route without having to use IdentityDbContext?

public class MyEntities : DbContext
{
     public DbSet<AspNetUsers> AspNetUsers { get; set; }
}
Erik Philips
  • 53,428
  • 11
  • 128
  • 150
J Weezy
  • 3,507
  • 3
  • 32
  • 88
  • Possible duplicate of [EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType](https://stackoverflow.com/questions/28531201/entitytype-identityuserlogin-has-no-key-defined-define-the-key-for-this-entit) – trailmax Jan 29 '18 at 11:10

3 Answers3

3

you don't need to add

public DbSet<AspNetUsers> AspNetUsers { get; set; }

inherit your context from IdentityDbContext to have only one context

public class MyEntities : IdentityDbContext<AspNetUsers>

also don't forget to set up UserManager to use your MyEntities context with AspNetUsers

Nikolai
  • 306
  • 1
  • 10
  • That worked, thank you sir. I had already taken care of the MyEntities context with AspNetUsers. But, it was all relevant so I mark yours as the answer. – J Weezy Feb 04 '18 at 22:56
2

You could avoid using the IdentityDbContext but you need to setup the mapping yourself in the OnModelCreating method within your DbContext class.

However, if you are using the SignInManager etc.. I recommend you use the IdentityDbContext. You are not constraint to use Code-First Migrations.

1

Identity context inherits from DBContext. Hence as long as your own db context inherits from identity context, it should be enough. Something like following :-

public class MyDbContext : IdentityContext {}
qamar
  • 1,437
  • 1
  • 9
  • 12
  • This was also part of the answer, but Nikolay provided additional context that was necessary. I thank you for responding to this post. – J Weezy Feb 04 '18 at 22:58