IdentityUserLogin<string>' requires a primary key to be defined error while adding migration
Entity FrameworkEntity Framework Problem Overview
I am using 2 different Dbcontexts. i want to use 2 different databases users and mycontext. While doing that i am getting a error The entity type 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin
My Dbcontext class:
class MyContext : DbContext
{
public DbSet<Post> Posts { get; set; }
public DbSet<Tag> Tags { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<PostTag>()
.HasKey(t => new { t.PostId, t.TagId });
modelBuilder.Entity<PostTag>()
.HasOne(pt => pt.Post)
.WithMany(p => p.PostTags)
.HasForeignKey(pt => pt.PostId);
modelBuilder.Entity<PostTag>()
.HasOne(pt => pt.Tag)
.WithMany(t => t.PostTags)
.HasForeignKey(pt => pt.TagId);
}
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public AppUser User {get; set;}
public string Content { get; set; }
public List<PostTag> PostTags { get; set; }
}
public class Tag
{
public string TagId { get; set; }
public List<PostTag> PostTags { get; set; }
}
public class PostTag
{
public int PostId { get; set; }
public Post Post { get; set; }
public string TagId { get; set; }
public Tag Tag { get; set; }
}
and AppUser class:
public class AppUser : IdentityUser
{
//some other propeties
}
when I try to Add migration the following error occurs.
The entity type 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>' requires a primary key to be defined.
give me solution to resolve the issue..
Entity Framework Solutions
Solution 1 - Entity Framework
To reduce the link to a nutshell, try this:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
...
See Above link for more.
Solution 2 - Entity Framework
This issue will start coming as soon as you wrote the following lines in DBContext without adding 'base.OnModelCreating(modelBuilder);'
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
}
Two solutions:
-
Don't override
OnModelCreating
in DbContextUntil it becomes necessary
-
Override but call
base.OnModelCreating(modelBuilder)
Solution 3 - Entity Framework
The problem is AppUser is inherited from IdentityUser and their primary keys are not mapped in the method OnModelCreating of dbcontext.
There is already a post available with resolution. Visit the below link
Hope this helps.