IdentityUserLogin' requires a primary key to be defined error while adding migration

entity-framework

Question

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' requires a primary key to be defined. I think there is something wrong with IdentityUser please suggest me where can i change my code so that i can add migration.

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..

1
67
9/30/2016 6:55:32 PM

Accepted Answer

To reduce the link to a nutshell, try this:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

    ...

See Above link for more.

190
12/5/2017 9:09:20 PM

Popular Answer

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:

1) Don't override OnModelCreating in DbContext Until it becomes necessary

2) Override but call base.OnModelCreating(modelBuilder)



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow