None of the similair questions seem to be able to solve this problem. I'm using Entity Framework 5, MVC 4, .NET 4.5 for my web app, designed with VS 2012.
I have 2 classes that are supposed to be in a parent-child relationship.
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
// Other stuff
public int? JoggerId { get; set; }
public virtual Jogger Jogger{ get; set; }
}
and
public class Jogger
{
[Key]
public int JoggerId { get; set; }
[Required, ForeignKey("UserId")]
public int UserId { get; set; }
public virtual UserProfile UserProfile { get; set; }
}
With Fluent API:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<UserProfile>()
.HasOptional(x => x.Jogger)
.WithRequired(c => c.UserProfile)
.WillCascadeOnDelete(true);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
base.OnModelCreating(modelBuilder);
}
A User can be a Jogger but can also not be a Jogger i.e. one User to zero or one Jogger. the relationship looks fine on the EF Powertools edmx view but I cannot get the Foreign key to work with the UserProfile UserId.
Is my Fluent API wrong or is it my models? Please help - I am truly stuck!