1. ホーム
  2. entity-framework

[解決済み] IdentityUserLogin<string>」は、マイグレーション追加時にプライマリキーの定義が必要なエラー [重複] が発生する。

2023-01-27 06:34:15

質問

私は2つの異なるDbcontextsを使用しています。私は2つの異なるデータベースusersとmycontextを使用したいと思います。その際、The entity type 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin' requires a primary key to be definedというエラーが発生しました。私は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.

問題を解決するためのソリューションを教えてください。

どのように解決するのですか?

を減らすには リンク を一言で言うと、こうしてみてください。

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

    ...

詳しくは上記リンク先をご覧ください。