使用EF核心与对象一对多关系

时间:2020-10-19 10:55:18

标签: sql database entity-framework relational-database

我有四个实体:

员工:它属于集团和部门实体 组:包含员工列表 部门:包含员工列表 待办事项:已分配给组

问题是:我试图将FK添加到表中,并且像其他10种方法一样,但我只是想不通。让我们看一下部门:

public class Department
    {
        public Department()
        {
            Employees = new List<Employee>();
        }

        [Key]
        public int DepartmentId { get; set; }

        [Required]
        public string Name { get; set; }

        [Required]
        public string Field { get; set; }

        public ICollection<Employee> Employees { get; set; }
    }

这是Employee实体:

public class Employee
    {
        public int EmployeeId { get; set; }

        [Required]
        [MaxLength(50, ErrorMessage = "Name cannot exceed 50 characters")]
        public string Name { get; set; }

        [Required]
        [RegularExpression(@"^[a-zA-Z0-9_0+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$", ErrorMessage = "Invalid Email Format")]
        [Display(Name = "Office Email")]
        public string Email { get; set; }

        [ForeignKey("Department")]
        public int DepartmentId { get; set; }

        public Department Department { get; set; }

        [ForeignKey("Group")]
        public int GroupId { get; set; }

        public Group Group { get; set; }
    }

我为部门生成了一个简单的控制器和查看页面 在详细信息方法中,我尝试打印出department.Employees.Count(),但显示为0。

这是我的appDbContext:

modelBuilder.Entity<Employee>()
                .HasData(
                new Employee() { EmployeeId = -99, Name = "Mary", Email = "mary@gmail.com", DepartmentId = -99, GroupId = -1 },
                new Employee() { EmployeeId = -98, Name = "Stan", Email = "stan@gmail.com", DepartmentId = -99, GroupId = -1 },
                new Employee() { EmployeeId = -97, Name = "Mike", Email = "mike@gmail.com", DepartmentId = -99, GroupId = -1 });

            modelBuilder.Entity<Department>()
                .HasData(
                new Department() { DepartmentId = -99, Field = "IT", Name = "Programming Department" },
                new Department() { DepartmentId = -98, Field = "HR", Name = "Human Resorcues" },
                new Department() { DepartmentId = -97, Field = "AD", Name = "Advertisement Department" });

1 个答案:

答案 0 :(得分:1)

您的问题有很多“漏洞”,您仍必须尝试并学习。因此,如果您需要更多帮助,此问题将得到更新。

我认为您在理解对象方面遇到麻烦。

例如,如果您想在自己的工作中做,则该部门有一份员工名单(如我在声明中所见):

但是:

   public List<Employee> Employees 
    {
      get; set;
    }

然后:

 new Department() { DepartmentId = -99, Field = "IT", Name = "Programming Department", Employees = x },

其中x是保留或本身就是实例或List:

modelBuilder.Entity<Employee>()
                .HasData(
                new Employee() { EmployeeId = -99, Name = "Mary", Email = "mary@gmail.com", DepartmentId = -99, GroupId = -1 },
                new Employee() { EmployeeId = -98, Name = "Stan", Email = "stan@gmail.com", DepartmentId = -99, GroupId = -1 },
                new Employee() { EmployeeId = -97, Name = "Mike", Email = "mike@gmail.com", DepartmentId = -99, GroupId = -1 })

但是,使用E.F.数据库更容易:

//Save your employee in the context.
_context.Employees.Add(newemployee);
//Set the employee in the departament
thedepartament.Employees.Add(newemployee); 
//Save everything
_context.SaveChanges();

更新:

当然,您每次“添加”新的“雇员”时都不会创建部门,上面的示例仅用于同时插入一个关系孩子。因此,您需要以这种方式思考:

//Save your employee in the context.
_context.Employees.Add(newemployee);
//Search for the departament you want to add this employee, with a query:
Departament thedepOfTheNewEmployee = _context.Departament.Where(your conditions to search it).FirstOfDefault();
//Set the employee to that departament
newemployee.DepartmentId = thedepOfTheNewEmployee.Id;
//Save everything
_context.SaveChanges();

更多理论:
如果将元素添加到上下文中,将(虚拟)提供要检索的ID。该理论不适用于您的情况,但将来会为您提供帮助。