IdentityUserLogin < string >’在添加迁移时需要定义一个主键错误

我正在使用两种不同的 Dbcontext。我想使用2个不同的数据库用户和我的上下文。在这样做的时候,我得到了一个错误的实体类型’微软。AspNetCore.身份。实体框架核心。IdentityUserLogin’需要定义一个主键。我认为有一些错误的身份用户请建议我在哪里可以改变我的代码,以便我可以添加迁移。

我的 Dbcontext 类:

 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; }
}

及 AppUser 类别:

public class AppUser : IdentityUser
{
//some other propeties
}

当我尝试添加迁移时,会发生以下错误。

The entity type 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>' requires a primary key to be defined.

给我解决问题的办法。

67330 次浏览

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

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

Hope this helps.

To reduce the link to a nutshell, try this:

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


...

See Above link for more.

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)