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
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()
.HasOptional(x => x.Department)
.WithMany()
.HasForeignKey(x => x.DepartmentID);
And for department use:
modelBuilder.Entity()
.HasOptional(x => x.Manager)
.WithMany()
.HasForeignKey(x => x.ManagerID);
modelBuilder.Entity()
.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 Employees { get; set;}
And mapping should be modified to:
modelBuilder.Entity()
.HasOptional(x => x.Department)
.WithMany(y => y.Employees)
.HasForeignKey(x => x.DepartmentID);