I am using EntityFramework 4.1.
I have the following model:
public class User
{
[Key]
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public virtual User Creator { get; set; }
public virtual User LastEditor { get; set; }
}
When I try to generate my database I got this error:
Unable to determine the principal end of an association between the
types ‘User’ and ‘User’. The principal end of this association must be
explicitly configured using either the relationship fluent API or data
annotations.
But I also have this class:
public class Course
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public virtual User Creator { get; set; }
public virtual User LastEditor { get; set; }
}
And it works ok, I have these foreign keys generated:
Creator_Id
LastEditor_Id
Do I have anything to add in my User model to make it works?
EF tries – by convention – to create a one-to-one relationship between
User.CreatorandUser.LastEditorbecause they both refer to theUserclass where they are themselves located in. That’s not the case for theCourseclass. ForCourse.CreatorandCourse.LastEditorEF creates two one-to-many relationships to theUser. To achieve the same for the properties inUseryou will have to configure the relationships with Fluent API: