I am trying to model a “User can have 0 or 1 set of preferences” where the preferences table has a primary key of UserId which is also a foreign key to the User entity, a la this post.
I want my model something like:
public class User
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public virtual int Id { get; set; }
[Required]
public virtual string Username { get; set; }
public virtual UserPreferences Preferences { get; set; }
}
public class UserPreferences
{
[Key]
public User User { get; set; }
public bool SubscribedToNewsLetter{ get; set; }
}
with config:
HasOptional(u => u.Preferences).WithRequired(l => l.User);
yields:
SetUp : System.Data.Entity.ModelConfiguration.ModelValidationException : One or more validation errors were detected during model generation:
System.Data.Edm.EdmEntityType: : EntityType 'UserPreferences' has no key defined. Define the key for this EntityType.
System.Data.Edm.EdmEntitySet: EntityType: EntitySet �UserPreferences� is based on type �UserPreferences� that has no keys defined.
You must define a key in
UserPreferences: