Working with entity framework code first.
Trying to use the IdentityRole id as a foreign key to a custom class.
the relationship is correct but when I try to add data to my custom table i get this error.
EntityType 'IdentityUserRole' has no key defined. Define the key for this EntityType. IdentityUserRoles: EntityType: EntitySet 'IdentityUserRoles' is based on type 'IdentityUserRole' that has no keys defined.
Code:
Custom table/class
public class UserRoleAccess
{
[Key]
public long UserRoleAccessId { get; set; }
public string UserRoleId { get; set; }
public virtual ApplicationRole ApplicationRole { get; set; }
public bool IsActive { get; set; }
public string Name { get; set; }
public int UserRoleAccessType { get; set; }
}
IdentityRole:
public class ApplicationRole : IdentityRole
{
public virtual ICollection<UserRoleAccess> UserRoleAccess { get; set; }
}
Bindings:
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<IdentityUser>().ToTable("Users").Property(p => p.Id).HasColumnName("UserId");
modelBuilder.Entity<ApplicationUser>().ToTable("Users").Property(p => p.Id).HasColumnName("UserId");
modelBuilder.Entity<IdentityUserRole>().ToTable("UserRoles");
modelBuilder.Entity<IdentityUserLogin>().ToTable("UserLogins");
modelBuilder.Entity<IdentityUserClaim>().ToTable("UserClaims");
modelBuilder.Entity<IdentityRole>().ToTable("Roles");
modelBuilder.Entity<ApplicationRole>().ToTable("Roles");
modelBuilder.Entity<UserRoleAccess>().ToTable("UserRoleAccess");
modelBuilder.Entity<ApplicationUser>().HasRequired(p => p.Person)
.WithMany(b => b.Users);
modelBuilder.Entity<ApplicationUser>().HasRequired(p => p.Person)
.WithMany(b => b.Users)
.HasForeignKey(p => p.PersonId);
modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);
modelBuilder.Entity<IdentityRole>().HasKey<string>(r => r.Id);
modelBuilder.Entity<ApplicationRole>().HasKey<string>(r => r.Id);
modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });
}
Relationship in db(correct):
Tried creating an id property and setting a [Key] attribute but it did not work:
public class ApplicationRole : IdentityRole
{
[Key]
public string Id { get; set; }
public virtual ICollection<UserRoleAccess> UserRoleAccess { get; set; }
}
Run this code when adding data:
public static void CreateUserRoleAccess(string name, int type, string id)
{
using (var context = new UserRoleAccessContext())
{
var userRoleAccess = new UserRoleAccess();
userRoleAccess.ApplicationRole = new ApplicationRole { Id = id };
userRoleAccess.UserRoleId = id;
userRoleAccess.IsActive = true;
userRoleAccess.UserRoleAccessType = type;
userRoleAccess.Name = name;
context.UserRoleAccess.Add(userRoleAccess);
context.SaveChanges();
}
}
What am I missing?
EDIT:
IdentityRole class:


