I have looked up and down, tried all the different and various ways of being able to store a foreign key of the AspNetUser table in a separate Customer table. I\'m still new
In a one-to-one relation the "child" table, in your case Customer
, should have the same primary key as the related table, i.e. the foreign key.
The code sample you have supplied means that, in Customer
you will have a PK named CustomerID
which is different from UserId
.
This should work in your case (untested):
public class Customer
{
[Key]
public string UserId { get; set; }
[ForeignKey("UserId")]
public virtual ApplicationUser ApplicationUser { get; set; }
}
public class ApplicationUser : IdentityUser
{
public virtual Customer Customer { get; set; }
}
Edit:
MSDN for ForeignKeyAttribute states:
If you add the ForeigKey attribute to a foreign key property, you should specify the name of the associated navigation property. If you add the ForeigKey attribute to a navigation property, you should specify the name of the associated foreign key(s).
I interpret this as that it should be possible to add the ForeignKey-attribute to either the navigation property or the foreign key property, and that either way should work, but apparently not. Moving it as per below should do the trick.
public class Customer
{
[Key, ForeignKey("ApplicationUser")]
public string UserId { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}
public class ApplicationUser : IdentityUser
{
public virtual Customer Customer { get; set; }
}