0

my code is:

public class UserGroupUser
{
    public int UserGroupUserId { get; set; }
    public string UserId { get; set; }
    [Key, ForeignKey("UserId")]
    public virtual ApplicationUser ApplicationUser { get; set; }
}

and when I try to create a controller I get this error:

EntityType 'IdentityUserLogin' had no key defined.Define the key for this entity type.

EntityType 'IdentityUserRole' had no key defined.Define the key for this entity type.

EntityType 'IdentityUserLogins' is based on 'IdentityUserLogin' that has no key defined.

EntityType: EnititySet 'IdentityUserRoles' is based on 'IdentityUserRole' that has no key defined.

but I can see the keys in my Database in SQL server management for all tables. how can I solve this problem?

Ilya Chumakov
  • 23,161
  • 9
  • 86
  • 114
amir mola
  • 355
  • 1
  • 4
  • 17
  • You have to specify primary keys for your EF entities by using `Id` property or `[Key]` attributes. Also it looks like you are using ASP.NET Identity, is it correct? If yes, pay attention to https://stackoverflow.com/questions/28531201/entitytype-identityuserlogin-has-no-key-defined-define-the-key-for-this-entit – Ilya Chumakov May 28 '17 at 14:49
  • Don't use `[Key]` on a nav property. Try `[Key, ForeignKey("ApplicationUser ")]` on the UserId property. – Steve Greene May 28 '17 at 16:02

2 Answers2

0

Entity need a primary key. Change your other models accordingly.

public class UserGroupUser
{
    [Key]
    public int UserGroupUserId { get; set; }
    public string UserId { get; set; }
    [ForeignKey("UserId")]
    public virtual ApplicationUser ApplicationUser { get; set; }
}
Ppp
  • 1,015
  • 9
  • 14
  • thank you @Ppp for the answer. you are right. the [key] was missing in my code. but actually the problem was something else. although this problem is solved before in other posts, I will write it as another answer. – amir mola May 29 '17 at 08:18
0

It turns out that EF doesn't recognize the keys in IdentityUserLogin, IdentityRole, IdentityUserRole tables(and I don't know the reason). so I had to tel it that those tables already have keys by overriding OnModelCreating method in my MainContext class(inherited from System.Data.Entity.DbContext):

public class MainContext : DbContext
{
    public MainContext() : base("MyDatabaseConnectionString") { }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        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 });
        base.OnModelCreating(modelBuilder);
    }

    public DbSet<UserGroup> UserGroups { get; set; }
    public DbSet<UserGroupUser> UserGroupUsers { get; set; }

}

seems this method executes before generating the database.

amir mola
  • 355
  • 1
  • 4
  • 17