Problem modelling relationship in Entity Framework using code first

前端 未结 2 479
醉梦人生
醉梦人生 2021-01-17 22:54

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

2条回答
  •  借酒劲吻你
    2021-01-17 23:37

    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);
    

提交回复
热议问题