I am using Entity Framework Core 2.1 and I have a class,
public class MyDbContext : IdentityDbContext<User>
The User table is part of the 1 and same database. In the Entity User class, it is defined as
public class User : IdentityUser
When I run and call userManager.FindByNameAsync(model.Username)
,I get following error:
IdentityUser IdentityDbContext<> Getting IdentityUserLogin requires primary key to be defined.
I googled and read someone's article on a possible solution. He said to use the following constructor
public DXContext(): base("name=DXContext")
{
Database.SetInitializer<DXContext>(null);// Remove default initializer
Configuration.ProxyCreationEnabled = false;
Configuration.LazyLoadingEnabled = false;
}
In my constructor, I am passing the connector string as follow
public MyDbContext()
{
}
// context being added and passing to connection string to use
public MyDbContext(DbContextOptions<ASLDbContext> options) : base(options)
{
// Database.SetInitializer<MyDbContext>(null);
}
I get a build error on SetInitializer method as follows:
DatabaseFacade does not contain the definition for SetInitializer.
Any help will be appreciated to resolve the IdentityUserLogin
primary key issue.
Update your startup.cs
user AddDefaultIdentity<User>()
instead of AddDefaultIdentity<IdentityUser>
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDbContext<MyDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<User>()
.AddEntityFrameworkStores<MyDbContext>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
Your DbContext
can as simple as this
public class MyDbContext : IdentityDbContext<User>
{
public MyDbContext(DbContextOptions<MyDbContext> options)
: base(options)
{
}
}
Your extended user class
public class User : IdentityUser
{
public string SomeAdditionalProperty { get; set; }
}
_LoginPartial.cshtml
Change the IdentityUser
to your User
class.
@inject SignInManager<User> SignInManager
@inject UserManager<User> UserManager
These 4 changes is all that is needed to get Identity working with an extended class (User
) over the base IdentityUser
when starting from a brand new project with authentication built-in.