I am trying to create navigation properties for my collection types, and I found this example of how one person executed it using OnModelCreating. I tried the MVC 5 application and got this error while trying to update my database:
During model generation, one or more validation errors were detected:
BlogEngine.Models.IdentityUserLogin :: EntityType 'IdentityUserLogin' is not defined by key. Define a key for this EntityType. BlogEngine.Models.IdentityUserRole :: EntityType 'IdentityUserRole' is not defined by key. Define a key for this EntityType. IdentityUserLogins: EntityType: EntitySet 'IdentityUserLogins' is based on the type 'IdentityUserLogin', which does not have specific keys. IdentityUserRoles: EntityType: EntitySet 'IdentityUserRoles' is based on the type 'IdentityUserRole', which does not have specific keys.
How to resolve these "Keyless" errors?
I did a few searches and I found this solution for one user problem, but his needs were different than mine. The solutions seemed rather confusing for what I'm trying to do.
This is the code that causes the problem:
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 models with many for many relationships:
Post.cs Model in Gist
Tag.cs ββModel in Gist
Refresh to show IdentityUser:
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
}
source
share