Reputation: 11
I have created an MVC 5 site using Identity 2.0. I am using integer for primary key.
When I try to create a Model with an association to ApplicationUser I get the following error:
EntityType 'ApplicationUserRole' has no key defined.
What do I need to do to fix this error?
IdentityModels.cs
public class ApplicationUserLogin : IdentityUserLogin<int> { }
public class ApplicationUserClaim : IdentityUserClaim<int> { }
public class ApplicationUserRole : IdentityUserRole<int> { }
public class ApplicationRole : IdentityRole<int, ApplicationUserRole>, IRole<int>
{
public string Description { get; set; }
public ApplicationRole() : base() { }
public ApplicationRole(string name) : this()
{
this.Name = name;
}
public ApplicationRole(string name, string description) : this(name)
{
this.Description = description;
}
}
public class ApplicationUser : IdentityUser<int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>, IUser<int>
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager)
{
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
public string FullName { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
}
Employee.cs
public class Employee
{
public int Id { get; set; }
public string Title { get; set; }
public virtual ApplicationUser User { get; set; }
}
Upvotes: 0
Views: 948
Reputation: 31
You will need to override the OnModelCreating method to define the primary keys:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ApplicationUserLogin>().HasKey<int>(l => l.UserId);
modelBuilder.Entity<ApplicationRole>().HasKey<int>(r => r.Id);
modelBuilder.Entity<ApplicationUserRole>().HasKey(r => new { r.RoleId, r.UserId });
}
Here's a similar thread: User in Entity type MVC5 EF6
Upvotes: 3