Entity Framework In MVC - Part Seven

In the previous article, I explained, how to perform CRUD and how to perform searching functionality using the code-first approach and Repository using single table. In this article, I will explain how to create relationship among more than one table. Let’s see step by step.

In the previous article, I explained how to perform CRUD and how to perform searching functionality using the code-first approach, and Repository using a single table. In this article, I will explain how to create relationships among more than one table. Let’s see step by step.

See the previous articles for basic details.

Entity framework supports three types of relationships,

  1. One-to-Many,
  2. One-to-One
  3. Many-to-Many.

Now, first, we will start with one-to-many relationships. In this article, we will create two classes, first is Employee and second is Education.

Entity Framework

 

In the above figure, Employee and Education entities have a one-to-many relationship denoted by multiplicity where 1 is for One and * is for Many. This means that Employee can have many Education details whereas Eductation can associate with only one Employee.

Generally, when we create relationships then we have to create first class and we have to add properties, and after that we have to decorate with Attributes as needed.

So now we will see a practical example.

Open Visual Studio and go to File >> Project >> Web application and click OK. Then, it will open a window. In that window, select MVC or Empty.

Now we will add two classes in the Model folder, Employee, and Education

Employee.cs

  1. [Table("TblEmployee")]  
  2.  public class Employee  
  3.  {  
  4.      [Key]  
  5.      public int EmpId { get; set; }  
  6.      [Required()]  
  7.      [StringLength(100, MinimumLength = 4)]  
  8.      public string Name { get; set; }  
  9.      [Required()]  
  10.      [StringLength(200, MinimumLength = 10)]  
  11.   
  12.      public string Address { get; set; }  
  13.      [Required()]  
  14.      [StringLength(200, MinimumLength = 5)]  
  15.      public string Email { get; set; }  
  16.      [Required()]  
  17.      [StringLength(10, MinimumLength = 10)]  
  18.   
  19.      public string MobileNo { get; set; }  
  20.      public List<Education> educations { get; set; }  
  21.  }  

Educations.cs

  1. [Table("TblEducation")]  
  2. lic class Education  
  3.  {  
  4.      public int EducationId { get; set; }  
  5.      [Required()]  
  6.      [StringLength(100, MinimumLength = 4)]  
  7.      public string EduName { get; set; }  
  8.      [Required()]  
  9.      [StringLength(100, MinimumLength = 4)]  
  10.      public string UniversityName { get; set; }  
  11.      [Required()]        
  12.      [DataType(DataType.Date)]  
  13.      public DateTime PassOut { get; set; }  
  14.      public Employee employee { get; set; }  
  15.  }  

We can see the relationship.

Entity Framework

 

After that, we will update the database using data migration.

So, Go to tool >>NuGet Package Manager >> Package Manager Console and type the below command

Update-Database

Entity Framework

 

After that, we will check in SQL server.

Entity Framework

 

And we can see the relationship. Right click on tblEducation table and go design and right click employee_EmpId and see the relation.

Entity Framework

 

Now, we will go to project and open EmpDataContextInitializer class and set some default records.

  1. public class EmpDataContextInitializer : DropCreateDatabaseAlways<EmpDataContext>  
  2.   {  
  3.       protected override void Seed(EmpDataContext context)  
  4.       {  
  5.           
  6.           Employee empObj = new Employee {EmpId=1, Name = "Mithilesh", Address = "Hyderabad Telangana", Email = "mithilesh@gmail.com", MobileNo = "9823423432" };  
  7.             
  8.           context.employees.Add(empObj);  
  9.   
  10.           context.educations.Add(new Education()  
  11.           {  
  12.               EmpId = 1,  
  13.               EduName = "BCA",  
  14.               UniversityName = "Patna University",  
  15.               PassOut = Convert.ToDateTime("05-07-2010")  
  16.   
  17.   
  18.           });  
  19.           context.educations.Add(new Education()  
  20.           {  
  21.               EmpId = 1,  
  22.               EduName = "MCA",  
  23.               UniversityName = "BPUT University",  
  24.               PassOut = Convert.ToDateTime("05-07-2010")  
  25.           });  
  26.           Employee empObj1 = new Employee {EmpId=2, Name = "Rohan", Address = "Banglore Karnatka", Email = "rohan@gmail.com", MobileNo = "9823423432" };  
  27.   
  28.           context.employees.Add(empObj1);  
  29.   
  30.           context.educations.Add(new Education()  
  31.           {  
  32.               EmpId = 2,  
  33.               EduName = "MCA",  
  34.               UniversityName = "Kuvempu University",  
  35.               PassOut = Convert.ToDateTime("05-07-2010")  
  36.           });  
  37.           context.SaveChanges();  
  38.       }  
  39.   }  

After that we will go to the Global.asax file and add the below line inside the Application_Start().

  1. Database.SetInitializer<EmpDataContext>(new EmpDataContextInitializer());  

Now, go to the model folder and add EmpDataContext class and write the below code.

  1. public class EmpDataContext : DbContext  
  2.     {        
  3.         public EmpDataContext()  
  4.             : base("name=MySqlConnection")  
  5.         {  
  6.              
  7.         }  
  8.         public DbSet<Employee> employees { get; set; }  
  9.         public DbSet<Education> educations { get; set; }  
  10.     }  

After that we will go to model folder and will add an Employee Repository class and add the below code.

  1. public class Repository<T> where T : class  
  2. {  
  3.     EmpDataContext objDataContext = null;  
  4.     protected DbSet<T> DbSet  
  5.     {  
  6.         get;set;  
  7.     }  
  8.     public Repository()  
  9.     {  
  10.         objDataContext = new EmpDataContext();  
  11.        DbSet = objDataContext.Set<T>();  
  12.     }  
  13.   
  14.     public Repository(EmpDataContext objDataContext)  
  15.     {  
  16.         this.objDataContext = objDataContext;  
  17.     }  
  18.     public List<T> GetAll()  
  19.     {  
  20.         return DbSet.ToList();  
  21.     }  
  22.   public void Delete(T entity)  
  23.     {  
  24.         DbSet.Remove(entity);  
  25.     }  
  26.     public T GetById(int id)  
  27.     {  
  28.         return DbSet.Find(id);  
  29.     }  
  30.     public void SaveChanged()  
  31.     {  
  32.         objDataContext.SaveChanges();  
  33.     }  
  34. }  

Now, we will add a controller and create methods for employee details and according to the employee we have to see education details.

  1. public class DemoController : Controller  
  2.   {  
  3.       EmployeeRepository objRepository = new EmployeeRepository();  
  4.       // GET: Demo  
  5.       public ActionResult EmpDetails()  
  6.       {  
  7.          return View(objRepository.GetAll());                   
  8.            
  9.       }  
  10.       public ActionResult EduDetails(string id)  
  11.       {  
  12.           int empId = Convert.ToInt32(id);  
  13.           var emp = objRepository.GetById(empId);  
  14.           return View(emp);  
  15.       }  
  16.       }  
  17. blic ActionResult Delete(string id)  
  18.       {  
  19.           int empId = Convert.ToInt32(id);  
  20.           var emp = objRepository.GetById(empId);  
  21.           return View(emp);  
  22.       }  
  23.       [HttpPost]  
  24.       public ActionResult Delete(Employee objEmp)  
  25.       {  
  26.           var emp = objRepository.GetById(objEmp.EmpId);  
  27.           objRepository.Delete(emp);  
  28.           objRepository.SaveChanged();  
  29.           return View("EmpDetails");  
  30.       }  
  31.   
  32.   }  

Now, we will add a view for Employee details and Education details.

So, for that first Right click on EmpDetails and add HTML code for the view.

  1. @model IEnumerable<Example3.Models.Employee>  
  2.   
  3. <p>  
  4.     @Html.ActionLink("Create New""Create")  
  5. </p>  
  6.   
  7. <table class="table">  
  8.     <tr class="btn-primary">  
  9.         <th>  
  10.             @Html.DisplayNameFor(model => model.EmpId)  
  11.         </th>  
  12.         <th>  
  13.             @Html.DisplayNameFor(model => model.Name)  
  14.         </th>  
  15.         <th>  
  16.             @Html.DisplayNameFor(model => model.Address)  
  17.         </th>  
  18.         <th>  
  19.             @Html.DisplayNameFor(model => model.Email)  
  20.         </th>  
  21.         <th>  
  22.             @Html.DisplayNameFor(model => model.MobileNo)  
  23.         </th>  
  24.         <th>Action</th>  
  25.     </tr>  
  26.   
  27. @foreach (var item in Model) {  
  28.     <tr class="btn-info">  
  29.         <td>  
  30.             @Html.DisplayFor(modelItem => item.EmpId)  
  31.         </td>  
  32.         <td>  
  33.             @Html.DisplayFor(modelItem => item.Name)  
  34.         </td>  
  35.         <td>  
  36.             @Html.DisplayFor(modelItem => item.Address)  
  37.         </td>  
  38.         <td>  
  39.             @Html.DisplayFor(modelItem => item.Email)  
  40.         </td>  
  41.         <td>  
  42.             @Html.DisplayFor(modelItem => item.MobileNo)  
  43.         </td>  
  44.         <td>  
  45.             @Html.ActionLink("Details""Details"new { id = item.EmpId })   
  46.         </td>  
  47.     </tr>  
  48. }  
  49.   
  50. </table>  

And then we will add Education details view page. Right click and add HTML code.

  1. @model Example3.Models.Employee  
  2.   
  3. <div>  
  4.     <h4>Employee</h4>  
  5.     <hr />  
  6.     <dl class="dl-horizontal">  
  7.         <dt>  
  8.             @Html.DisplayNameFor(model => model.Name)  
  9.         </dt>  
  10.   
  11.         <dd>  
  12.             @Html.DisplayFor(model => model.Name)  
  13.         </dd>  
  14.   
  15.       <dd>  
  16.           <ul>  
  17.               <b>Education Details</b>  
  18.               @foreach (var edu in Model.educations)  
  19.               {  
  20.                   <li>@edu.EduName,@edu.UniversityName,@edu.PassOut</li>  
  21.                   
  22.               }  
  23.           </ul>  
  24.       </dd>  
  25.   
  26.     </dl>  
  27. </div>  

Now, finally run the project and see the output.  We get an error.

Entity Framework

 

Here it's giving the error “Object reference not set to an instance of an object”

Why did we get a null reference error?

Entity Framework uses lazy loading by default.

It is the default behavior of an Entity Framework. “Lazy loading” means that the related data is transparently loaded from the database when the navigation property is accessed. It delaying the loading of related data until you specifically request for it. For more information click this link.

Here, Employee entity contains the Education entity. In the lazy loading, the context first loads the Employee entity data from the database, and then it will load the Education entity when we access the Education property.

How do we support lazy loading?

Mark all complex type properties as virtual.

Can we disable lazy loading?

Ans: Yes

Now how do we solve that?

  • Add a property for the key of the primary object:- EmpId for Employee
  • Entity Framework will automatically pick this up based on convention:- Use the ForignKeyAttribute if we need to change the name

Now, again go back in our project and make it virtual of reference properties in both Employee and Education and then add EmpId inside the Education details.

So, first open the Education class and change it to virtual like the below example.

Entity Framework

 

Again open Employee class and change it to virtual.

Entity Framework

Now, run the project and see the output.

Entity Framework

When we will click details then we will see the output like below.

Entity Framework

Now check in the database also.

Entity Framework
 
Entity Framework

Now we will delete our records so first, we have to make sure Cascade delete is set to true.

So, open sql server and right click on tblEducation table and right click on EmpId and select relationship and go to Insert and Update specific option and set Cascade in Delete Rule.

Entity Framework

After that, save the table and go in our application output, click on Delete button, and after that see the output.

Entity Framework

Summary

In this article, we saw how to create one-to-many relationships using a Code First approach. In our next article, we will see one-to-one and many-to-many relationships.