Introduction
In simple terms, the
Code First approach in Entity Framework is a way of creating a database and its tables using C# code and Entity Framework classes. For this approach, we will first consider the tables for storing the data, then we will design the classes depending on requirements. In these articles, I will show you in very simple ways and I hope you will be able to understand all the concepts.
Important for you
Before learning we will first consider the classes very important for the Code First approach:
- DBContext
- DBSet
I will explain in very few words, if you want to learn more about DBContext and DBSet then
Click.
But don’t think this class isn't used in the Database First approach and Model First approach. It is used but you don't care about these classes.
DBContext
- It works to convert a LINQ to Entity query to a SQL query and send it to the database.
Note: Please don't be confused about the entity. “An entity is a class defined for mapping into a table.” If you are confused about what an entity is then don't worry, I will explain it in a very simple way with an example.
- It does insert, update, and delete operations on the database based on the entity.
- It keeps track of changes that occurred in the entities after it has been retrieved from the database.
DBSet
The DBSet class represents an entity set to create, read, update, and delete operations.
Now let’s do it.
Step 1
Go to "File" -> "New" -> "Project..." and add a console application.
Step 2
Now right-click on the References folder and use the NuGet package for installing the Entity Framework DLL. If you do not have NuGet then download the Entity Framework DLL from Google and add to the references folder.
Step 3
Now look into your references folder and find the Entity Framework DLL as in the following:
In the preceding image the second highlighted assembly is for annotation. This is essential for you. If it's is not available then add it from the .Net assembly.
Right-click on the references folder then click on Add reference then in the .Net tab choose it.
Step 4
Now add two class named "Employee" and “Department”.
- using System.ComponentModel.DataAnnotations;
- using System.ComponentModel.DataAnnotations.Schema;
-
- namespace CodeFirstApproachInEntityFramework
- {
- public class Employee
- {
- [Key]
- public int EmployeeID { get; set; }
- public string Name { get; set; }
- public int Age { get; set; }
- public string Gender { get; set; }
- [ForeignKey("Department")]
-
- public int DepartmentID { get; set; }
-
- public Department Department { get; set; }
-
- }
- }
-
- using System.ComponentModel.DataAnnotations;
- using System.ComponentModel.DataAnnotations.Schema;
-
- namespace CodeFirstApproachInEntityFramework
- {
- public class Department
- {
- [Key]
- public int DepartmentID { get; set; }
- public string DepartmentName { get; set; }
-
-
- }
- }
Annotation
Annotation provides constraints on classes and properties like [Key].
[Required],[MaxLength(50)], here the [Key] attribute maps into the database as a Primary key for the EmployeeID and DepartmentID coloumns.
For Foreign Key you use System.ComponentModel.DataAnnotations.Schema namespace.
Step 5
Now add a new class and provide the name "EmployeeContext" as in the following:
Step 6
Add an App.Config file and add a connection string as in the following:
- <connectionStrings>
- <add name="DBCS" connectionString="SERVER=piyush-pc;DATABASE=EntityDB;USER ID=sa;PASSWORD=pass.123" providerName="System.Data.SqlClient"/>
- </connectionStrings>
Note: Before running this program you need to create a database named
EntityDB.
Step 7
Now write the following code in the console application.
- using System;
- using System.Collections.Generic;
-
- namespace CodeFirstApproachInEntityFramework
- {
- class Program
- {
- static void Main(string[] args)
- {
-
- using (EmployeeContext cx = new EmployeeContext())
- {
-
-
-
-
-
- IList<Department> department = new List<Department>
- {
- new Department{DepartmentID=1,DepartmentName="IT"},
- new Department{ DepartmentID=2, DepartmentName="HR"},
- new Department{ DepartmentID=3, DepartmentName="Account"}
- };
- cx.Departments.AddRange(department);
- cx.SaveChanges();
-
-
- Employee employee = new Employee();
- employee.EmployeeID = 1;
- employee.Name = "Mohit";
- employee.Age = 21;
- employee.Gender = "Male";
- employee.DepartmentID = 1;
- cx.Employees.Add(employee);
- cx.SaveChanges();
-
- Console.WriteLine("Tables have created successfully.");
- }
- Console.ReadKey();
- }
- }
- }
Note: Here I am not handling the primary key conflict sinice if you insert employeeID=1 again then it will throw an error.
Step 8
After successfully running, go to SQL Server Management Studio and open your EntityDB database and look.
So in the preceding I attempted to explain everything in a very easy way. I hope you enjoyed it.