Entity Relationship Using EF Core Code First Approach

 In this section, we are going to talk about the different kind of relationship between entities and how to establish that using C# code.

Followings are the type of relationship

One to Many

An employee can have more than 1 education details. To Achieve this, we need to have a property in employee class like the below one.

public ICollection<EmployeeEducation> EducationList { get; set; }

Once we do this and add the migration, it will add a new column EmployeeID in EmployeeEducations table, but as a nullable attribute.

In this case, if we try to add data in EmployeeEducations table, it will set EmployeeID as null

To fix this, we need to add a cross reference in the EmployeeEducation Class, to denote that Every education record must have an employee ID. This will ensure that allow null attribute of EmployeeID column in EmployeeEducations  table is set to false.

public Employee Employee { get; set; }

If we try to insert values in EmployeeEducations table with below code, it won't work because of foreign key reference error.


 List<EmployeeEducation> educationList = new List<EmployeeEducation>();
        educationList.Add(new EmployeeEducation { CourseName = "BCA", UniversityName = "Manipal", 
            MarksPercentage = 80, PassingYear = 2020 });
        educationList.Add(new EmployeeEducation { CourseName = "MCA", UniversityName = "Manipal", 
            MarksPercentage = 75, PassingYear = 2022 });

        CrudEducationDetails obj = new CrudEducationDetails();
        obj.InsertEducation(educationList);


 public void InsertEducation(List<EmployeeEducation> educationList)
        {
            demoDbContext.EmployeeEducations.AddRange(educationList);
            demoDbContext.SaveChanges();
        }


To Fix the error, we need to ensure that we pass the employee object also when we try to save data in EmployeeEducations Table


 Employee employee = new Employee { Name = "Abhimanyu", Address = "Delhi" };
        
        List<EmployeeEducation> educationList = new List<EmployeeEducation>();
        educationList.Add(new EmployeeEducation { CourseName = "BCA", UniversityName = "Manipal", 
            MarksPercentage = 80, PassingYear = 2020, Employee = employee });
        educationList.Add(new EmployeeEducation { CourseName = "MCA", UniversityName = "Manipal", 
            MarksPercentage = 75, PassingYear = 2022 , Employee = employee});

        CrudEducationDetails obj = new CrudEducationDetails();
        obj.InsertEducation(educationList);

 public void InsertEducation(List<EmployeeEducation> educationList)
        {
            demoDbContext.EmployeeEducations.AddRange(educationList);
            demoDbContext.SaveChanges();
        }

We can also insert data in both tables using a different approach

  List<EmployeeEducation> educationList = new List<EmployeeEducation>();
        educationList.Add(new EmployeeEducation { CourseName = "BCA", UniversityName = "Manipal", MarksPercentage = 80, PassingYear = 2020 });
        educationList.Add(new EmployeeEducation { CourseName = "MCA", UniversityName = "Manipal", MarksPercentage = 75, PassingYear = 2022 });

        obj.InsertEmployeeAndEducation(new Employee { Name = "Manish", Address = "Pune" }, educationList);

public void InsertEmployeeAndEducation(Employee employee, List<EmployeeEducation> educationList)
        {
            var objEmployee = new Employee
            {
                Name = employee.Name,
                Address = employee.Address,
                EducationList = educationList

            };

            demoDbContext.Employees.Add(objEmployee);
            demoDbContext.SaveChanges();
        }



One to One

Let's consider 2 entities ClassRoom and Teacher for 1-1 relationship. To establish this, we should add a type of another class in both classes like below.

public class ClassRoom

    {

        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]

        [Key]

        public int ID { get; set; }

        [Column(TypeName = "Varchar(50)")]

        public string? Name { get; set; }

        public Teacher Teacher { get; set; }

    }

 public class Teacher

    {

        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]

        [Key]

        public int ID { get; set; }

        [Column(TypeName = "Varchar(50)")]

        public string? Name { get; set; }

        public ClassRoom ClassRoom { get; set; }

    }

Migration will not work, because the code is unable to identify which table should be treated for primary key and which for foreign key.

To Fix this, we must make changes in any of the class. Let's add a new property in the ClassRoom Class and run the migration.

public int TeacherID { get; set; }

Many to Many

If we want to establish many to many relationship between 2 tables, then we should add an attribute of ICollection type in both classes

public void InsertClassRoomAndTeacher(ClassRoom classRoom, List<Teacher> teachers)

        {

            var objClassRoom = new ClassRoom

            {

                Name = classRoom.Name,

                Teachers = teachers

            };

            demoDbContext.ClassRooms.Add(objClassRoom);

            demoDbContext.SaveChanges();

        }

Rest of things will work similar to 1 to many relationship.



Reference Link: https://www.youtube.com/watch?v=eHT6G912po0

Source Code Link:  https://github.com/kumarabhimanyu/EFCoreWithEntityRelationship


Comments

Popular posts from this blog

Publish .Net Core Web API to Linux Host

Web API Using EF Core