7

コレクション型のナビゲーション プロパティを作成しようとしてきましたが、OnModelCreating を使用して 1 人がそれを達成した方法の例を見つけました。MVC 5 アプリケーションで試してみたところ、データベースを更新しようとしたときに次のエラーが発生しました。

モデルの生成中に 1 つ以上の検証エラーが検出されました:

BlogEngine.Models.IdentityUserLogin: : EntityType 'IdentityUserLogin' にはキーが定義されていません。この EntityType のキーを定義します。BlogEngine.Models.IdentityUserRole: : EntityType 'IdentityUserRole' にはキーが定義されていません。この EntityType のキーを定義します。IdentityUserLogins: EntityType: EntitySet 'IdentityUserLogins' は、キーが定義されていないタイプ 'IdentityUserLogin' に基づいています。IdentityUserRoles: EntityType: EntitySet 'IdentityUserRoles' は、キーが定義されていないタイプ 'IdentityUserRole' に基づいています。

これらの「キーが定義されていません」エラーを解決するにはどうすればよいですか?

私はいくつかの検索を行い、あるユーザーの問題に対してこの解決策を見つけましたが、彼のニーズは私のものとは異なりました. 私がやろうとしていることに対して、解決策はかなり複雑に見えました。

これは問題を引き起こすコードです:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {

        }
        //public DbSet<Image> Images { get; set; }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }

        public DbSet<Post> Posts { get; set; }
        public DbSet<Image> Images { get; set; }
        public DbSet<Album> Albums { get; set; }
        public DbSet<Tag> Tags { get; set; }

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

            modelBuilder.Entity<Post>().
                 HasOptional(e => e.Tags).
                 WithMany().
                 HasForeignKey(m => m.Tags_Id);

            modelBuilder.Entity<Tag>().
                 HasOptional(e => e.Posts).
                 WithMany().
                 HasForeignKey(m => m.Posts_Id);
        }

    }

多対多の関係を持つ私の to モデルは次のとおりです。

Gist の Post.cs モデル

Gist の Tag.cs​​ モデル


IdentityUser を表示するように更新します。

public class ApplicationUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }
4

3 に答える 3

15

次のようなものを追加する必要があるかもしれませんOnModelCreating

modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);
modelBuilder.Entity<IdentityRole>().HasKey<string>(r => r.Id);
modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });

以下も参照してください。

于 2015-05-20T20:06:10.877 に答える
10

base問題は、からクラスの呼び出しを削除したことだと思いますOnModelCreating。以下に示すように、それも追加してみてください

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

        //Your configuration goes here
    }
于 2017-10-25T08:15:13.783 に答える