Home  >  Article  >  Backend Development  >  Entity Framework C#

Entity Framework C#

王林
王林Original
2024-09-03 15:20:00999browse

The following article provides an outline for Entity Framework C#. Entity Framework is an Object Relational Mapping (ORM) that helps to enhance the user’s app productivity by eliminating the redundant job in the application. EF builds the required DB Commands for writing or reading the data in DB and executes them perfectly. Finally, EF executes the query in DB and makes the results into domain objects to work with the application.

What is Entity Framework in C#?

Entity Framework is an Object-Source Relational Mapping (ORM) Framework for .Net Applications, which allows the developers to work on relational data by using the domain-specific object without the knowledge of the columns and tables of the database where the data gets stored. Furthermore, it depicts that the Entity Framework minimizes the codes of data accessing that the developers usually write.

Entity Framework in C# Projects

Let’s assume the Department and the Employee table tables consider like the table contains the records of several departments and the employees of various departments.

To achieve this, we must build the Department and the Employee classes. Then, to retrieve those data from the database, we need to code ADO.NET. Finally, when the data is retrieved, we have to create objects of Employee and Department to populate them with recovered data.
The above entire thing is tedious, but through Entity Framework, it is easy; those things can be done automatically; we need to provide DB Schema to EF. Let’s see the following steps to create an application using EF.

To create the database schema, make use of the SQL Script to create the database EF_Demo_DB and also to create tables of Employee and Department

Code:

-- to create the Database EF_Demo_DB
CREATE DATABASE EF_Demo_DB;
GO
-- Use EF_Demo_DB database
USE EF_Demo_DB;
GO
-- to Create the table Departments
CREATE TABLE Departments
(
ID INT PRIMARY KEY IDENTITY(1,1),
Name VARCHAR(50),
Location VARCHAR(50)
)
Go
-- to Create the table Employees
CREATE TABLE Employees
(
ID INT PRIMARY KEY IDENTITY(1,1),
Name VARCHAR(50),
Email VARCHAR(50),
Gender VARCHAR(50),
Salary INT,
DepartmentId INT FOREIGN KEY REFERENCES Departments(ID)
)
Go
-- --to Populate the table with few records
INSERT INTO Departments VALUES ('HR', 'Bangalore')
INSERT INTO Departments VALUES ('Sales', 'Cochin')
INSERT INTO Departments VALUES ('IT', 'Chennai')
Go
--to Populate the table with few records
INSERT INTO Employees VALUES ('Philip', '[email protected]', 'Male', 45000, 2)
INSERT INTO Employees VALUES ('Mary', '[email protected]', 'Female', 30000, 2)
INSERT INTO Employees VALUES ('Valarie', '[email protected]', 'Female', 35000, 3)
INSERT INTO Employees VALUES ('John', '[email protected]', 'Male', 80000, 1)
INSERT INTO Employees VALUES ('Joseph', 'jojog.com', 'Male', 60000, 1)
INSERT INTO Employees VALUES ('Steve', '[email protected]', 'Male', 45000, 3)
INSERT INTO Employees VALUES ('Peter', '[email protected]', 'Male', 60000, 1)
INSERT INTO Employees VALUES ('Rio', '[email protected]', 'Female', 345000, 3)
INSERT INTO Employees VALUES ('Ben', '[email protected]', 'Male', 70000, 1)
Go

To Create the Console Application

Once the data is ready, create a new Console Application with the name of EFDemo as shown below:

Entity Framework C#

To Add the ADO.NET Entity Data Model

To create the Console Application add the ADO.NET Entity Data Model and right-click on the project and Add -New Item-Data- ADO.NET Entity Data Model and make the name as EmployeeDataModel as shown below.

Entity Framework C#

Once click on Add button, select the EF Designer from Database and click the Next button as shown below to choose the EF Designer from the database; here, we are using EF Database First Approach.

Entity Framework C#

Once clicking on the Next button, it asks you to choose the data connection wizard as shown; click on the New Connection button.

Entity Framework C#

Once click on that New Connection button, provide the necessary database details and finally, “Test Connection” and click OK.

Entity Framework C#

Select the Data Connection and save the entity connection settings in App. Then, config as shown below, give the name EF_Demo_DBEntities and click the Next button.

Entity Framework C#

Here it asks you to select the Entity Framework 6.x and select the Next button as shown.

Entity Framework C#

Choose the desired tables, change the Model Namespace to “EmployeeModel,” and click on the Finish button as shown.

Entity Framework C#

Clicking on the Finish button generates the EmployeeDataModel.edmx file.

Entity Framework C#

This is the structure of the EDMX file as shown below,

Entity Framework C#

Using the EF, we created the application.

Code:

namespace EFDemo
{
class Program
{
static void Main(string[] args)
{
using (EF_Demo_DBEntities DBEntities = new EF_Demo_DBEntities())
{
List<Department> listDepartments = DBEntities.Departments.ToList();
Console.WriteLine();
foreach (Department dept in listDepartments)
{
Console.WriteLine(" Department = {0}, Location = {1}", dept.Name, dept.Location);
foreach (Employee emp in dept.Employees)
{
Console.WriteLine("\t Name = {0}, Email = {1}, Gender = {2}, salary = {3}",
emp.Name, emp.Email, emp.Gender, emp.Salary);
}
Console.WriteLine();
}
Console.ReadKey();
}
}
}
}

Database Mode and Classes

Entity Framework Features:

Let’s see the features of Entity Framework:

  • Modelling: EF builds an EDM based on the attributes with the get/ set properties of various data types. It uses the model if storing or querying the entity data to the database.
  • Querying: Entity Framework enables LINQ queries to get the data from the database. The DB providers translate the queries of LINQ to DB-specific query language. EF allows to execution of the SQL queries to the DB.
  • Change Tracking: Entity Framework follows the changes that occurred to the case of the property values which required to be submitted to DB.
  • Storing: Entity Framework executes the commands of INSERT, DELETE and UPDATE to the database based on modifying the entities while calling the SaveChanges() method. In addition, entity Framework EF offers the SaveChangesAsync() method.
  • Concurrency: Entity Framework uses optimistic concurrency by default to secure the changes through another user since data was fetched from DB.
  • Caching: Entity Framework includes the initial level of caching out of the box. So the query returns the data from the cache instead of hitting DB.
  • Configuration: Entity Framework enables configuring the EF model using the Data Annotation attributes or API to override the conventions by default.
  • Built-in Conventions: Entity Framework follows a convention through the programming configuration pattern and contains the default rules that automatically configure the EF Model.

Conclusion

In this article, we saw the features of EF and how to create the Entity Framework. However, using ADO.NET code is tedious when compared with EF. Also, it is a time-consuming, error-prone process, so Microsoft offers a Framework called Entity Framework to automate the entire DB-related work for our application.

The above is the detailed content of Entity Framework C#. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Assembly Reference in C#Next article:Assembly Reference in C#