I\'m trying to learn code first within the Entity Framework and am having trouble modelling a relationship. It\'s a basic HR database which for the sake of this has two enti
See your employee class
EMPLOYEE
public int? DepartmentID { get; set; }
public virtual Department Department { get; set; }
In order to show the relationship between an employee and a department you used ID and Department. In reality you only need to do this once - via Department
. EF by default searches for the ID property and links two classes for you. So your classes should only include one ID - ID of the class itself. Try removing IDs to the other classes.
That because your model configuration is incomplete - you started your own mapping with Fluent API so you must tell EF that these properties are indeed FKs for relations. For employee use:
modelBuilder.Entity<Employee>()
.HasOptional(x => x.Department)
.WithMany()
.HasForeignKey(x => x.DepartmentID);
And for department use:
modelBuilder.Entity<Department>()
.HasOptional(x => x.Manager)
.WithMany()
.HasForeignKey(x => x.ManagerID);
modelBuilder.Entity<Department>()
.HasOptional(x => x.TeamAdministrator);
.WithMany()
.HasForeignKey(x => x.TeamAdministratorID);
Btw. without collection navigation properties on opposite side of relations it will be hard to use model (all WithMany
are empty). At least Department
should have:
public virtual ICollection<Employee> Employees { get; set;}
And mapping should be modified to:
modelBuilder.Entity<Employee>()
.HasOptional(x => x.Department)
.WithMany(y => y.Employees)
.HasForeignKey(x => x.DepartmentID);