简体   繁体   中英

One to many relationship with objects using EF core

I have four entities:

Employee: It belongs to Group and Department entities Group: Contains a list of Employees Department: Contains a list of Employees Todo: Assigned to a Group

The thing is: I tried to add FK to the tables and like 10 other approaches but I just can't figure it out. Let's see for example Department:

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

And here is the Employee entity:

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

I generated a simple controller and view page for Departments and in the details method I try to print out the department.Employees.Count() but it says it's 0.

Here is my 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" });

Your question has a lot of "holes" and you must still trying and learning. So this question will be updated if you need more asistance.

I think you are having troubles to understand objects.

If you want to do it in your eg, the departament has a list of employees (as I can see in your statement):

But:

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

and then:

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

where x is an instance or List that keep or is this itself:

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

But for database is more easy with EF:

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

UPDATE:

Of course you won't create a departament everytime you "add" a new "employee", the above example is only for insert a relation child at the same time. So what you need is thinking in this way:

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

More further theory:
If you Add your element to the context, will be provided (virtually) an Id to retrieve. This theory is not for your scenario, but will help you in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM