I'm using code first to create a foreign key on YogaSpace
that links the ApplicationUsers
id to ApplicationUserRefId
in the YogaSpace
class. So every time I create and insert a new YogaSpace
it fills the ApplicationUser
id with the id of the person logged in. And I want it to be a one-to-many where the YogaSpace
object can be many for one ApplicationUser
id. But I'm getting key errors.
public class YogaSpace
{
// for a one-to-one relationship
// great tutorial on code-first
//http://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-first.aspx
[Index (IsUnique = true)]
[Key]
[Column(Order = 1)]
public int YogaSpaceId { get; set; }
[Key]
[Column(Order = 2)]
public int ApplicationUserRefId { get; set; }
[ForeignKey("ApplicationUserRefId")]
public virtual ApplicationUser ApplicationUser { get; set; }
[Required]
public string Name { get; set; }
}
Here is my ApplicationUser
class
public class ApplicationUser : IdentityUser
{
//other members left out to save space
public virtual ICollection<YogaSpace> YogaSpaces { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
Here are all the errors. When updating the database, it's throwing related to keys.
One or more validation errors were detected during model generation:
GiftExchange.DataLayer.Models.IdentityUserLogin: : EntityType 'IdentityUserLogin' >has no key defined. Define the key for this EntityType. GiftExchange.DataLayer.Models.IdentityUserRole: : EntityType 'IdentityUserRole' >has no key defined. Define the key for this EntityType.
UPDATE! I tried overriding the class that its asking me to create a key for but it still doesn't work
public class TestIdentityUserLogin : IdentityUserLogin
{
[Key]
public override string UserId { get; set; }
}
I tried adding the keys using fluent api found in this link [User in Entity type MVC5 EF6
In my YogaSpaceContext
I included
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);
modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });
}
and it seemed to remove the no key defined errors from the package manager for updating the database. But how would I implement it in code first?