Entity Framework for Data Access in ASP.Net MVC

Sidenote : This is the part 6 of the ASP.Net MVC course series.  You can get all the parts of this tutorial here.

Entity framework is one of the data access framework provided by Microsoft. You can use this framework to get data from the database and save the updated data back into the database.

Sidenote: Entity Framework is not related to ASP.Net MVC framework – you can use it with any type of application say Console app, Windows service,Web App,Web Api etc..  In fact, ASP.Net MVC is data access methodology agnostic – it doesn’t care/know what you use to access the data.

You may wonder why we have to go for this new framework when we have been doing fine with ADO.Net.

What is the problem it solves which ADO.Net does not? To put it in simple words, what is the purpose of existence of Entity framework?

Let us take an example of saving employee information to the database. Below are the steps that you used to do.

  1. You’ll have business objects(Employee object with update phone number) in our application
  2. You create and open a connection to the database
  3. You create command of type stored procedure (SP which updates phonenumber or saving entire employee object)
  4. We would convert the fields in Employee object to add them as SQL Parameters of the command object
  5. The command is executed
  6. If that stored procedure returns any data(if its select query or returns some value which needs to be displayed), you need to get that result and display the result

These are high level steps – based on your requirements the number of steps may increase/decrease.

Let us see how we can do it using Entity Framework

  1. You’ll have business objects(Employee object with update phone number) in our application – Same as ADO.Net step
  2. Just save the object using DBContext.
  3. Steps Involved in Entity Framework

Yes. That’s it. Does it seem magical?

In the background, EF(Entity framework) creates a database connection and creates query for saving your employee object. It then executes the query against your intended database and fetches you the result.

If it seems vague, don’t worry.

Seeing example will make this clear.

Let us create a simple console application which uses Entity Framework.  You need to have Visual Studio Express for Windows Desktop downloaded and installed on your PC.

EF New Project

Open Package Manager Console by selecting Tools -> Nuget Package Manager -> Package Manager Console.
Nuget Package Mgr Option

You can give command “Install-Package EntityFramework” to install the Entity Framework package. It will download the latest stable Entity Framework and it will be added to your project.

Downloading EF 6.1.2 status

I have created simple class file to represent movie information- Movie. This class is just a business model class and has nothing to do with the Entity Framework.

Entity Framework has DbContext API, which helps you to query the database, perform the CRUD operations on the database. It also performs object tracking, optimization among other things.

In order to use DbContext API, you need to do the following steps.

  1. DbContext is available in System.Data.Entity namespace. You need to include this namespace if you use DbContext.
  2. Create a class (MovieDBContext in below code) which inherits from DbContext so that we can use the methods of DbContext API.
  3. Have all the classes(only Movie class in our case) which you want to persist/query the database using DbSet.

Below is the complete code – It’s tiny but does the job.

We have set everything in order to use DbContext API of Entity framework. We just have to use that to interact with database.

Let’s write client application which use our DBContext API.

We are creating Movie object and then call Add method of DbSet which adds the object to the Context and mark it as Added state for that object. Till now, Entity framework will not interact with the database and everything happens in memory.

When you call savechanges of DbContext class, Entity framework will save all the unsaved changed being tracked by DBContext API. At this point- it will insert our object (which is marked as Added) to the database.

You run this application and our Movie object would be saved to the database.

Let us verify whether the data is saved correctly in database. Open your SQL Server Express Management Studio.

You could see the database created by name EF.MovieDBContext(in YourAppName.DBContextName format) and a table created with our class name pluralized (Movies) and all the properties that we have in our class would be acting as columns in created table.

Database table screenshot

You can even query the database to confirm whether the data is saved successfully.

Movie resultset query

That’s it. You have created your first Entity framework application.

Congrats. Pat on your back.

When you follow closely, we didn’t give any information about the database. No connection string.

But yet Entity framework handled everything (including creating this new database) and inserted the data into the database without any issues.

Is it some form of Magic? Yes, but not black magic.

Let us go behind the curtains and see what has happened.

When you use Entity framework, following are the sequence of event that would happen

  1. When you add Entity framework to your application, it will add respective configuration in your App.config(if its console app –as in our case) or web.config(if its web app).

By default, it will use the Sqlconnectionfactory as connection factory and sqlclient as provider – meaning that it will use SQL Express if it exists in the system where you are running the application. However, you can override this setting if you want.

2.   It connects to the database using Windows Authentication. You can verify this by viewing properties of the database – The owner of the database would be like {DesktopName}\{LoginId}

SQL Express Login

3. It searches for database with name {AppName.ContextName}.If it doesn’t exist, it create a new database with that name.

In our case,it searches for ‘EF.MovieDBContext’. It created a new database as it was not available.

4. Then, it will take list of classes in DBContext which you have used DbSet. In our case, we have used only Movie class.

It will create a table with pluralized version of our class name and creates a table with that name. The properties of the class would become the columns of the table.

5. Based on the operation that we have done, it would construct the equivalent SQL query. We have performed ‘Add’ operation. So Entity framework would construct the insert SQL query and run it again the database. The property values (along with types) of our object in C# would become the column values (with types) in the table. If you use ‘int’ type for your property in your C#, your column in table will be of type int.

These are the high level sequence of events happen when we use Entity Framework in your application.

[button type=”flat” shape=”square” size=”large” href=”https://www.dotnetodyssey.com/asp-net-mvc-5-free-course/model/” title=”Previous chapter”]Previous Chapter[/button] [button type=”flat” shape=”square” size=”large” href=”https://www.dotnetodyssey.com/asp-net-mvc-5-free-course/” title=”Home”]Home[/button] [button type=”flat” shape=”square” size=”large” href=”https://www.dotnetodyssey.com/asp-net-mvc-5-free-course/css-and-twitter-bootstrap/” title=”Next Chapter”]Next Chapter[/button]


Leave a Reply

Your email address will not be published. Required fields are marked *