I have a new ASP.NET MVC 5.1 project using the ASP.Net Identity. It seems reliable and promise, but today i spend almost 9 hours to do a simple things if using SQL.
My problem is, i cannot create a table via CodeFirst with foreign key reference to the default AspNetUsers table.
For example: I have create a table named - Address
public class Address { [Key] public string UserId { get; set; } public string MyAddress { get; set; } }
But how can i create a foreign key reference to AspNetUsers?
I try replace the property above by
public IdentityUser MyAddress { get; set; } // Or public virtual IdentityUser MyAddress { get; set; } // Or public virtual ApplicationUser MyAddress { get; set; }
But all of them still show error:
One or more validation errors were detected during model generation: MiaPos.Models.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType. MiaPos.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.
I also try override the OnModelCreating from this post
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 }); }
But when i run Add-Migration, it create the IdentityUserLogin, IdentityRole, IdentityUserRole tables and it duplicate, just the prefix is different. (AspNet<->Identity)
Finally i do it by SQL in 10 seconds, but i just want to know why i cannot do in CodeFirst? And why so hard to do a such things from Microsoft 2014 New Technology.
You can do like this. because sometime you may need 1-1 connection
public class AnotherTable { [Key] public string UserId { get; set; } [ForeignKey("UserId")] public virtual ApplicationUser User { get; set; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With