Resolving 'No key Defined' errors while using OnModelCreating with ApplicationDbContext?

11,456

Solution 1

You might have to add something like the following to 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 });

See also:

Solution 2

I think the issue is that you have removed the calling of base class from OnModelCreating. Try adding that also as shown below

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

        //Your configuration goes here
    }

Solution 3

I know this is a late response, and this may only work for people working off tutorials or school projects!

For me, just deleting the database, .mdf, and migrations folder fixed it. Now, I don't know if you are using migrations, but this worked for me.

I'm a novice, but what I've noticed is that Identity is very finicky with keys. Deleting the migration has helped with every (godforsaken) migration problem I've hit with my project.

Share:
11,456
Dan Beaulieu
Author by

Dan Beaulieu

Working as a full-stack C# developer &amp; CTO at Xtrades C# Reactive Programming Dotnetcore Azure

Updated on June 25, 2022

Comments

  • Dan Beaulieu
    Dan Beaulieu almost 2 years

    I've been trying to create navigation properties for my collection types and I found this example of how one person accomplished it using OnModelCreating. I gave it a try in my MVC 5 application and I recieved this error when trying to update my database:

    One or more validation errors were detected during model generation:

    BlogEngine.Models.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType. BlogEngine.Models.IdentityUserRole: : EntityType 'IdentityUserRole' has no key defined. Define the key for this EntityType. IdentityUserLogins: EntityType: EntitySet 'IdentityUserLogins' is based on type 'IdentityUserLogin' that has no keys defined. IdentityUserRoles: EntityType: EntitySet 'IdentityUserRoles' is based on type 'IdentityUserRole' that has no keys defined.

    How do I resolve these 'No key Defined' errors?

    I did some searching and I found this solution for one users problem, but his needs were different than mine. The solutions seemed pretty convoluted for what I am trying to do.

    This is the code that causes the issue:

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

    Here are my to models with the many to many relationship:

    Post.cs model on Gist

    Tag.cs model on Gist


    Update to show 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;
            }
        }