Introduction
Entity Framework is an Object Relational Mapping (ORM) framework. ORM framework automatically makes classes based on database tables, and makes database tables based on classes. That is, it can also automatically generate necessary SQL to create database tables based on classes.
Patterns In Entity Framework
Data providers are source specific providers which abstract the ADO.NET interfaces to connect to the database when programming against the conceptual schema. It translates the common SQL languages such as LINQ via command tree to native SQL expression and executes it against the specific DBMS system. Entity Client layer exposes the entity layer to the upper layer. Entity client provides the ability for developers to work against entities in the form of rows and columns using Entity SQL queries without the need to generate classes to represent conceptual schema. Entity Client shows the entity framework layers which are the core functionality. These layers are called as Entity Data Model.
The Storage Layer contains the entire database schema in XML format.
The Entity Layer which is also an XML file defines the entities and relationships.
The Mapping layer is an XML file that maps the entities and relationships defined at conceptual layer with actual relationships and tables defined at logical layer.
The Metadata services which are also represented in Entity Client provide centralized API to access metadata stored Entity Mapping and Storage layers.
Object Services layer is the Object Context that represents the session of interaction between the applications and the data source. The main use of the Object Context is to perform different operations like add, delete instances of entities and to save the changed state back to the database with the help of queries. It is the ORM layer of Entity Framework that represents the data result to the object instances of entities. This service allows developers to use some of the rich ORM features like primary key mapping, change tracking, etc. by writing queries using LINQ and Entity SQL.
Entity Framework has the following three approaches,
- Schema First Approach
- Model First Approach
- Code First Approach
Schema First Approach
It can automatically generate necessary SQL to create database tables based on classes. Entity Framework can do all of the above automatically, if we provide it with the database schema.
The Database First Approach provides an alternative to the Code First and Model First approaches to the Entity Data Model.
It creates model codes like classes, properties, DbContext etc. from the database in the project and those classes become the link between the database and controller. The Database First approach creates the EF from an existing database. We use all the other functionalities, such as the model/database sync and the code generation, in the same way we used them in the Model First approach.
Model First Approach
In the Model First Approach, we first create the Entity Model.
- Entities
- Relationships between entities
- Inheritance hierarchies etc.
We implement all this directly on the design surface of the EDMX file.
The model is stored in an EDMX file and can be viewed and edited in the Entity Framework Designer. In Model First, you define your model in an Entity Framework designer then generate SQL, which will create database schema to match your model and then you execute the SQL to create the schema in your database. The classes that you interact with in your application are automatically generated from the EDMX file.
Code First Approach
Code-first approach allows us to create the custom classes first and based on these custom classes entity framework can generate database automatically for us successfully. Code First adds a model builder that inspects your classes that the context is managing, and then uses a set of rules or conventions to determine how those classes and the relationships describe a model, and how that model should map to your database. Code First has the ability to use that model to create a database if required. It can also update the database if the model changes, using a feature called Code First Migrations.
What is a EDMX
An .edmx file is an XML file that defines a conceptual model, a storage model, and the mapping between these models. An .edmx file also contains information that is used by the ADO.NET Entity Data Model Designer (Entity Designer) to render a model graphically.
Transaction
Whenever you run SaveChanges() to insert, update or delete the database, the framework will put that operation in a transaction. When you invoke SaveChanges, the context automatically starts a transaction and commits or rolls it back. Starting a transaction requires that the store connection is open. So calling "Database.BeginTransaction()" will open the connection if it is not already opened. If DbContextTransaction opened the connection, then it will close it when Dispose() is called.
Types of Entity Framework
In Entity Framework, there are two types of entities that use their own custom data classes together with data model without making any modifications to the data classes themselves.
- POCO entities
- Dynamic Proxy
POCO Entities
- POCO stands for "plain-old" CLR objects. POCO data classes which are mapped to entities are defined in a data model.
- It also supports most of the same query, insert, update, and delete behaviors as entity types that are generated by the Entity Data Model tools.
Dynamic ProxyWhile creating instances of POCO entity types , the Entity Framework often creates instances of a dynamically generated derived type that acts as a proxy for the entity. IT can also be said that it is a runtime proxy classes.
- You can override some properties of the entity for performing actions automatically when the property is accessed.
- This technique used to those models which are created with Code First and EF Designer.
Relationships In Entity FrameworkThere are three types of Relationships,
- One-to-Many Relationship
- Many-to-Many Relationship
- One-to-One Relationship
One-to-Many Relationship
A one-to-many relationship is the most common type of relationship. In this type of relationship, a row in table X can have many matching rows in table Y, but a row in table Y can have only one matching row in table X. The foreign key is defined in the table that represents the many ends of the relationship.
Many-to-Many Relationship
In many-to-many relationship, a row in table X can have many matching rows in table Y, and vice versa. You can create such a relationship by defining a third table, called a junction table, whose primary key consists of the foreign keys from both table X and table Y.
One-to-One Relationship
In a one-to-one relationship, a row in table X can have no more than one matching row in table Y, and vice versa. A one-to-one relationship is created if both of the related columns are primary keys or have unique constraints. In a one-to-one relationship, the primary key acts additionally as a foreign key and there is no separate foreign key column for either table.
DbContext In Entity Framework
Multiple DbContext was first revealed in Entity Framework 6.0. Multiple context classes may belong to a single database or two different databases.
Steps to create a simple application
Step 1
First create an MVC application named “MvcApplication2”.

Step 2
Then, create one table named “tblCustomers”.
Script for tblCustomers
CREATE TABLE [dbo].[tblCustomers](
[ID] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
[City] [nvarchar](50) NULL,
[Country] [nvarchar](50) NULL,
CONSTRAINT [PK_tblCustomers] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Enter some dummy records into this table.

Step 3
Then, create one stored procedure named “Sp_SearchCustomers”.
Script for Sp_SearchCustomers
CREATE PROCEDURE Sp_SearchCustomers
@City NVARCHAR(70)
AS
BEGIN
SET NOCOUNT ON;
SELECT * FROM tblCustomers
WHERE City LIKE '%' + @City + '%'
END
Here, I filtered the records based on City Column values.
Now, execute this stored procedure to filter records based on City Column values.
exec Sp_SearchCustomers 'Bangalore'
exec Sp_SearchCustomers 'Bhubaneswar'

Step 4
Follow these steps to create Entity Data Model.
So, create an ADO.NET Entity Data Model named “satyamodel.edmx”.

Then

Then, create a new connection using your SQL Server name and credentials using database name. You should select database where you created earlier created table and sp.

Now, select this table name as mentioned above.

You should now have the Entity Data Model ready with the tblCustomers Table.

Once the Entity Framework is configured, the next step is to import the Stored Procedure in the Entity Framework model. In order to do so, you will need to Right Click the Entity Model and select Update Model from Database option as shown below.

The above step will open the Update Wizard where you will need to select the above mentioned Stored Procedure and click Finish.

Now we will need to import the Stored Procedure into the Entity Framework so that it can be called as a Function using Entity Framework. Thus you will need to Right Click the Entity Model, click Add and then click Function Import.

This will open the Add Function Import dialog window. Here first you need to specify the Function Import Name which is the name of the function used to call the Stored Procedure and then select the Stored Procedure that will be executed when the function is called. The Return Type is selected as Entities which is the Customer Entity class.













DavidPosted May 6, 2018, 9:38 AM
Hi Satyaprakash, I was wondering, what is the best pattern for modifying data on mvc application ? Should I have sp’s ? Should I modify data directly with the dbcontext? That is something I still don’t get it. Thanks for your awesome article. Keep it up!
Bart VanPosted Jun 7, 2017, 5:26 PM
Hello Satyaprakash, I achieved to implement your article within my MVC application related to my customers list. When I try to implement this on my suppliers list, I receive the following error "The model item passed into the dictionary is of type 'System.Int32', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1". Could you indicate me what should be adapted in order to get this working on multiple pages within my MVC application?
Bart VanPosted May 13, 2017, 4:06 PM
Problem is that the end-user is not aware that he should use F5 when he want to clear the search field
Bart VanPosted May 13, 2017, 4:05 PM
Thank you for your reply.
kzelda linkPosted Apr 30, 2017, 5:37 AM
Great article , thx.
Bart VanPosted Apr 29, 2017, 4:56 PM
Great share!Just a small question, how do I add a clear button to have the overall customer list represented again? If I empty the search field and press the search button again, the list is displayed again.
Manav PandyaPosted Apr 29, 2017, 12:43 AM
Nice share ........................