Problem modelling relationship in Entity Framework using code first

前端 未结 2 478
醉梦人生
醉梦人生 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:30

    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.

    0 讨论(0)
  • 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<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);
    
    0 讨论(0)
提交回复
热议问题