IdentityUserLogin <string>'在添加迁移

时间:2016-09-30 18:55:33

标签: entity-framework

我正在使用2种不同的Dbcontexts。我想使用2个不同的数据库用户和mycontext。虽然这样做我收到错误实体类型'Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin'需要定义主键。我认为IdentityUser有问题请建议我在哪里可以更改我的代码,以便我可以添加迁移。

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

给我解决问题的解决方案..

3 个答案:

答案 0 :(得分:111)

要简化链接,请尝试以下方法:

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

    ...

请参阅以上链接了解更多信息。

答案 1 :(得分:17)

在DBContext中编写以下几行而不添加'base.OnModelCreating(modelBuilder);'

时,就会开始出现此问题。
protected override void OnModelCreating(ModelBuilder modelBuilder)
{

}

两种解决方案:

1)不要在DbContext OnModelCreating中覆盖Until it becomes necessary

2)覆盖,但致电base.OnModelCreating(modelBuilder)

答案 2 :(得分:7)

问题是AppUser是从IdentityUser继承的,它们的主键没有映射到dbcontext的OnModelCreating方法中。

已经有一个解决方案的帖子。请访问以下链接

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

希望这有帮助。