Before .NET 3.5 as a developer, we often used to write ADO.NET code to perform CRUD operation with the underlying database. For this, we need to create a connection with the database, open the connection, create a DataSet to fetch or submit the data to the database, and convert the data from the DataSet to .NET objects or vice-versa to apply our business rules. Actually, this was a time consuming, cumbersome, and error-prone process. Microsoft has provided a framework called “Entity Framework” to automate all these database related activities for our application if we provided the necessary details to the Entity Framework. In this article, I will give a brief Introduction to Entity Framework.
What is Entity Framework?
Entity Framework is an open-source object-relational mapping (ORM) Framework for .NET applications that enables .NET developers to work with relational data using domain-specific objects without focusing on the underlying database tables and columns where actually the data is stored. That means the Entity Framework eliminates the need for writing the data-access code that developers usually need to write.
Official Definition: “Entity Framework is an object-relational mapper (O/RM) that enables .NET developers to work with a database using .NET objects. It eliminates the need for most of the data-access code that developers usually need to write.”
What is the Object-Relational Mapping Framework?
Object Relational Mapping framework automatically creates classes based on database tables, and the vice versa is also true, that is, it can also automatically generate the necessary SQL to create database tables based on classes.
The following diagram illustrates where the Entity Framework fits into our application.
The above diagram states Entity Framework fits between the business entities (i.e. the domain classes) and the database. It saves the data in the database stored in the properties of the business entities (domain classes) and also retrieves the data from the database and converts it to business entities objects automatically.
Let’s understand what entity framework can do for us with an example.
Assume we have the following 2 tables
We want to display the above data from both the tables in a console application as shown below.
To achieve this
Step1: Use below SQL script to create the database, tables and populate the tables with some test data
Step 3: adding ADO.NET Entity Data Model Right-click on the project in solution explorer and select Add => New Item, and then click on Data Section from the left side panel and choose ADO.NET Entity Data Model middle panel, Change the name from Model1 to EmployeeDataModel as shown below.
Once we click on the Add button it will open Choose Data Model wizard as shown below.
From this window select EF Designer from the database and click on the Next button which will open choose your data connection wizard as shown below.
In this window first, click on New Connection which will open a popup for providing the database details as shown below.
From this connection properties screen,
Once we click on the Next button it will open a popup asking you to choose the Entity Framework version as shown below.
From this window select Entity Framework 6.x and click on the Next button which will open Choose Your Database Objects as shown below.
On this “Choose Your Database Objects” screen, select “Departments” and “Employees” tables. Change the Model Namespace to “EmployeeModel” and click the “Finish” button. At this point, you should have EmployeeDataModel.edmx created.
The following is the structure of our edmx file.
The Entity Framework Create Employee and Department classes automatically based on the Employees and Departments Tables. Tables are mapped to classes and columns are mapped to class properties.
Now copy and paste the following code in the main method of program class as shown below
If this is not clear at this moment how it works, then don’t worry we will discuss each and everything in detail in our upcoming articles.
Entity Framework Features:
Cross-platform: EF Core is a cross-platform framework which means it can run on Windows, Linux, and Mac operating systems.
Modeling: EF (Entity Framework) creates an EDM (Entity Data Model) based on POCO (Plain Old CLR Object) entities with get/set properties of different data types. It uses this model also when querying or saving entity data to the underlying database.
Querying: EF allows us to use LINQ queries (C#/VB.NET) to retrieve data from the underlying database. The database provider will translate these LINQ queries into the database-specific query language (e.g. SQL for a relational database). EF also allows us to execute raw SQL queries directly to the database.
Change Tracking: EF keeps track of changes that occurred to instances of our entities (Property values) that need to be submitted to the database.
Saving: EF executes INSERT, UPDATE, and DELETE commands to the database based on the changes that occurred to our entities when we call the SaveChanges() method. EF also provides the asynchronous SaveChangesAsync() method.
Concurrency: EF uses Optimistic Concurrency by default to protect overwriting changes made by another user since data was fetched from the database.
Transactions: EF performs automatic transaction management while querying or saving data. It also provides options to customize transaction management.
Caching: EF includes the first level of caching out of the box. So, repeated querying will return data from the cache instead of hitting the database.
Built-in Conventions: EF follows conventions over the configuration programming pattern, and includes a set of default rules which automatically configure the EF model.
Configurations: EF allows us to configure the EF model by using data annotation attributes or Fluent API to override default conventions.
In the next article, I will discuss the Architecture of the Entity Framework.
In this article, I try to explain Introduction to Entity Framework with an example. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article
Summary:
I hope this post will be helpful to understand the Introduction to Entity Framework
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
What is Entity Framework?
Entity Framework is an open-source object-relational mapping (ORM) Framework for .NET applications that enables .NET developers to work with relational data using domain-specific objects without focusing on the underlying database tables and columns where actually the data is stored. That means the Entity Framework eliminates the need for writing the data-access code that developers usually need to write.
Official Definition: “Entity Framework is an object-relational mapper (O/RM) that enables .NET developers to work with a database using .NET objects. It eliminates the need for most of the data-access code that developers usually need to write.”
What is the Object-Relational Mapping Framework?
Object Relational Mapping framework automatically creates classes based on database tables, and the vice versa is also true, that is, it can also automatically generate the necessary SQL to create database tables based on classes.
The following diagram illustrates where the Entity Framework fits into our application.
The above diagram states Entity Framework fits between the business entities (i.e. the domain classes) and the database. It saves the data in the database stored in the properties of the business entities (domain classes) and also retrieves the data from the database and converts it to business entities objects automatically.
Let’s understand what entity framework can do for us with an example.
Assume we have the following 2 tables
We want to display the above data from both the tables in a console application as shown below.
To achieve this
- We need to create Department and Employee classes
- We need to write ADO.NET code to retrieve the data from the database
- Once the data is retrieved we need to create Department and Employee objects and populate them with the retrieved data.
Step1: Use below SQL script to create the database, tables and populate the tables with some test data
IF EXISTS (SELECT * FROM sys.databases WHERE name = 'EF_Demo_DB') DROP DATABASE EF_Demo_DB; GO -- Create the School database. CREATE DATABASE EF_Demo_DB; GO -- Specify a simple recovery model -- to keep the log growth to a minimum. ALTER DATABASE EF_Demo_DB SET RECOVERY SIMPLE; GO USE EF_Demo_DB; GO -- Create Departments table CREATE TABLE Departments ( ID INT PRIMARY KEY IDENTITY(1,1), Name VARCHAR(50), Location VARCHAR(50) ) Go -- Create Employees table. 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 --Populate the Departments table with some test data INSERT INTO Departments VALUES ('IT', 'Mumbai') INSERT INTO Departments VALUES ('HR', 'Delhi') INSERT INTO Departments VALUES ('Sales', 'Hyderabad') Go --Populate the Employees table with some test data INSERT INTO Employees VALUES ('Mark', 'Mark@g.com', 'Male', 60000, 1) INSERT INTO Employees VALUES ('Steve', 'Steve@g.com', 'Male', 45000, 3) INSERT INTO Employees VALUES ('Pam', 'Pam@g.com', 'Female', 60000, 1) INSERT INTO Employees VALUES ('Sara', 'Sara@g.com', 'Female', 345000, 3) INSERT INTO Employees VALUES ('Ben', 'Ben@g.com', 'Male', 70000, 1) INSERT INTO Employees VALUES ('Philip', 'Philip@g.com', 'Male', 45000, 2) INSERT INTO Employees VALUES ('Mary', 'Mary@g.com', 'Female', 30000, 2) INSERT INTO Employees VALUES ('Valarie', 'Valarie@g.com', 'Female', 35000, 3) INSERT INTO Employees VALUES ('John', 'John@g.com', 'Male', 80000, 1) GoStep2: Create a new “Console Application” with name = EFDemo as shown below
Step 3: adding ADO.NET Entity Data Model Right-click on the project in solution explorer and select Add => New Item, and then click on Data Section from the left side panel and choose ADO.NET Entity Data Model middle panel, Change the name from Model1 to EmployeeDataModel as shown below.
Once we click on the Add button it will open Choose Data Model wizard as shown below.
From this window select EF Designer from the database and click on the Next button which will open choose your data connection wizard as shown below.
In this window first, click on New Connection which will open a popup for providing the database details as shown below.
From this connection properties screen,
- Select “Microsoft SQL Server” as Data source, and “.Net Framework Data Provider for SQL Server” option from the “Data provider” drop-down list. Click Continue.
- On the “Connection Properties” screen, specify SQL Server Name.
- Specify the Authentication you want to use.
- Select the database from “Select or enter a database name” drop-down list.
- Finally “Test connection” and click “OK”
Once we click on the Next button it will open a popup asking you to choose the Entity Framework version as shown below.
From this window select Entity Framework 6.x and click on the Next button which will open Choose Your Database Objects as shown below.
On this “Choose Your Database Objects” screen, select “Departments” and “Employees” tables. Change the Model Namespace to “EmployeeModel” and click the “Finish” button. At this point, you should have EmployeeDataModel.edmx created.
The following is the structure of our edmx file.
The Entity Framework Create Employee and Department classes automatically based on the Employees and Departments Tables. Tables are mapped to classes and columns are mapped to class properties.
Now copy and paste the following code in the main method of program class as shown below
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(); } } } }Run the application and notice that Departments and Employees data are displayed as expected. We have achieved all this without writing a single line of ado.net code.
If this is not clear at this moment how it works, then don’t worry we will discuss each and everything in detail in our upcoming articles.
Entity Framework Features:
Cross-platform: EF Core is a cross-platform framework which means it can run on Windows, Linux, and Mac operating systems.
Modeling: EF (Entity Framework) creates an EDM (Entity Data Model) based on POCO (Plain Old CLR Object) entities with get/set properties of different data types. It uses this model also when querying or saving entity data to the underlying database.
Querying: EF allows us to use LINQ queries (C#/VB.NET) to retrieve data from the underlying database. The database provider will translate these LINQ queries into the database-specific query language (e.g. SQL for a relational database). EF also allows us to execute raw SQL queries directly to the database.
Change Tracking: EF keeps track of changes that occurred to instances of our entities (Property values) that need to be submitted to the database.
Saving: EF executes INSERT, UPDATE, and DELETE commands to the database based on the changes that occurred to our entities when we call the SaveChanges() method. EF also provides the asynchronous SaveChangesAsync() method.
Concurrency: EF uses Optimistic Concurrency by default to protect overwriting changes made by another user since data was fetched from the database.
Transactions: EF performs automatic transaction management while querying or saving data. It also provides options to customize transaction management.
Caching: EF includes the first level of caching out of the box. So, repeated querying will return data from the cache instead of hitting the database.
Built-in Conventions: EF follows conventions over the configuration programming pattern, and includes a set of default rules which automatically configure the EF model.
Configurations: EF allows us to configure the EF model by using data annotation attributes or Fluent API to override default conventions.
In the next article, I will discuss the Architecture of the Entity Framework.
In this article, I try to explain Introduction to Entity Framework with an example. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article
Summary:
I hope this post will be helpful to understand the Introduction to Entity Framework
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
0 comments:
Post a Comment
If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.