Simplified CRUD Operation Using EntityFramework From Scratch

After reading this article, you will learn about;

  • Uses and purpose of LocalDb.
  • Connection string about LocalDb.
  • Model Binding.
  • DBContext
  • Step by step description of CRUD operation using LocalDb with Entity Framework.
  • What is Data Migration ?
  • How to migrate using Code First approach?

Note: Before we start, if you are new to ASP.NET MVC and you want a complete project as a reference, then click the download link for downloading the complete project.

Let’s start.

What is LocalDb and where does it exist?

In general, LocalDb is very similar to our SQL Server but LocalDb has some more limited features than SQL Server. LocalDb is only found inside Visual Studio. By default, Visual Studio provides one local server and local database in the development phase.

Local Server is called IIS Express while the local database is LocalDB. Both of these are pre-installed inside Visual Studio and help the developer to continue the development process even when Local IIS and SQL Server stop providing services.

Note: If you change the settings of the project to run it using Local IIS, then VisualStudio shows a pop-up window, as given below.

project

Click on No, here. If you click on Yes, then configuration is set for Local IIS.

This is the basic concept about Local DB. Ahead in this article, we will see where LocalDB exists and how to access it, so to see this live let’s start Visual studio to see the concept live. Open Visual Studio (I am using VS2013). Select New >> Project from file menu.

file

Then, give the project name as “CRUDDemo”.

CRUDDemo

Select ASP.NET Web Application and  select MVC template to create project. After successfully creating your project, go to Solution Explorer and check whether LocalDB is available inside App_Data folder or not. Because, as I told you, the default location of LocalDB is App_Data.

You cannot find any thing inside App_Data.The data present under App_Data folder is always hidden. So, click on "Show All Files" like below.

App_Data folder

We didn't find any file inside App_Data folder. So, let’s start creating Controller class and Model to get the DB file.

Add a Controller called BookController.

controller

controller

Choose Empty Controller and click on Add.

empty

Now, you get the BookController class created. Inside that, you get a default action method called as Index().

Now what do we do ?

These are our objectives to implement inside this project.

Objective 1 - Our first objective is to show the list of Book Details inside index page, using LocalDb and Entity Framework.

To do this, follow the below steps.

Step 1 - Add class for BookModel which contains all the properties for Book Details. So, go to Model folder and right click over it. Go to Add and click on Class.

Add class

Now, click on Class and give the class name as BookModel.

class

So, you got BookModel class. Now, add the below code inside Model.

BookModel class

In the above code, we see that there are two classes, BookModel.cs which represents as model for our CRUD operation, and BookDBContext.

So, what is the use of BookDBContext class?

The use of BookDBContextClass is to make DB operations using that class object. Due to this class inherited from DbContext class, it allows us to access all the methods of Dbcontext class.

DbContext class is specially designed for working with DB operation, using CodeFirst approach.

Note: Here, we inherited BookDBContext class explicitly from DbContext class because we are not going to use any Entity Framework template to generate the code implicitly. So, we write all the code manually.

Inside BookDBContext class, we have BookLst property of type Dbset which returns the list of Books.

Now, build your project -> Ctrl+shift+B.

After you succeed, add the below code inside BookController action method index().

code

In the above code, we have created BookDBConetext object called objBookDb; which helps us to provide different operations using it’s properties. In return, we are sending the list of Books to our View to see all the books.

Now, we can go to the RoutConfig.cs file and change the application route by specifying our Controller name and action method name as follows:

code

Now, if we directly run the application without adding View also, we can get our LocalDB inside App_Data folder. Before running the application, check once if the LocalDB exists or not.

We find that there is no LocalDB there but once you run the application, you can find LocalDB file inside App_Data folder.

When your app runs, due to no existing View, you get the exception that View is not found. Close the browser and come to Visual Studio. Check the LocalDB file with your DBContext class name created as below.

app data

Note: If you won’t find this file, then click on show all options in Solution Explorer, as shown above.

Now, we go to create a View page for Index action method which shows us the list of books.

To create view : Right click inside the Index action method and click on Add View. Then, you get a template that asks to bind your Model and add scaffolding template, as shown below.

app data

view

Inside Template, select “List”, model class as “Book”, and DataContext as “BookDB”.add view

Click on Add.

You get a nicely designed view called as Index.cshtml.

Now run your app,

You get Default page with strcture like bellow,

page

To Insert the data into LocalDb, we can use CreateNew link shown above but we don’t have any CreateNew page in our project. So, we can add this page later.

Why I am saying "later" is because here we can understand the DB Migration

We all generally know that we have two types of methods to insert the data. The first one is "using web page" while the second one is "to open SQL Server and write the SQL Query to insert the data".

But today, we will insert the data using another technique i.e using Seed() method of Migration class.

Don’tbe confused about seed() method. Here, we will see the live example of how seed method works when we do migration.

Let’s first understand what Migration is  and why we require it.

Migration is a technique that helps us to enable auto update to our DB while we are working with Entity Framework. In simple words, if we change anything inside our Model class and  want that same thing to be reflected inside our DB, then we are required to enable the migration feature for our project.

To enable migration for our Project, we need to open “Package Manger Console” and write the following command inside it.

Cmd : “enable-migrations –ContextTypeName Fully Qulified YourDBContextName”

For my project, I write the following cmd - “enable-migrations -ContextTypeName

CRUDDemo.Models.BookDBContext”

Package Manger Console

After running it, you get the below output.

output

After successfully enabling migration, we find a migration folder added inside the solution which contains two files, IntialCreate.cs and Configuration.cs.

migration

InitalCreate.cs file is the design View of our Model which is going to map the Database whereas Configuration.cs file plays an important role while working with migration. It contains a sealed class inherited from “DBMigrationConfiguration” class. That class contains the seed() method which I mentioned earlier.

Note: When we update the Database using update-database command, the seed() method executes automatically. So, it means seed() method is going to execute on execution of Update-Database command.

Earlier, I told you that we can insert data using Seed method to our Local Db. To do this, we need to replace the seed method code with the following code.

code

After adding this, Build your project.

Then again, open “Package Manager Console” and write the command “update-database”. After running this command, it will show you that the seed method is running.

method

After this, run your project. Here, you find two records showing inside the page which we have written under seed().

project

This is how we insert the data to Database. Now let’s do CRUD operation.

We already did Creation part using Seed(). I am skipping the CreateNew page and adding a new record. I am directly inserting data using Seed().

Now, we update the record using Edit Link. To do this, follow these steps.

Add Action method, Edit, as shown below.

code

Then, add a View for this action method. Here, I am using scaffolding to add the View. Right click inside action method and follow the below screenshot.

add a view

add a view

Now, select your Model class and click on Add button. You will get a nicely designed View.

Then, run your project and click on Edit. You will get the Edit page with the details.

project

When you click on Save button, you need to save it inside Database. For saving the data, we write another method using HttpPost attribute and give it the same name as edit.

Write the below code for Save Data.

code

Note: While calling method of BCL(for eg:- HttpStatusCodeResult), you get error due to namespace. To avoid this, write the method name correctly and press “ctrl+.(dot)” in that statement resolve using Visual Studio.

After writing the above code, run your application and edit your data and save it.

Now, the last operation that we need is Delete data.

To do this, add the following code.

code

Now, run your app and click on Delete button. Your record is deleted.

Now, let's see the last concept that is how to add migration file inside our project.

Before we see it live, first we need to understand why we need to add migration to our project or when do we need to add migration file to our project.

The purpose of generating migration file is to update our local Database when anything changes inside our Model clasas.

Note:- So, always keep in mind that the table where you are inserting the data, is created by using our current model class. Whenever you change anything inside model class, you are responsible to add new migration file to your project. The migration file contains information about your changes in model class. So, when we run the “update-database” command, then it automatically updates our Database by using our current change.

Let's see the concept with live example.

Go to BookModel.cs file and add a new property called Rating.

  1. public class BookModel  
  2.   
  3. {  
  4.   
  5. public int Id { getset; }  
  6.   
  7. public string BookName { getset; }  
  8.   
  9. public string AuthorName { getset; }  
  10.   
  11. public DateTime PublishDate { getset; }  
  12.   
  13. public int Rating { getset; }  
  14.   

 
Now build your project.
If we run now our project without adding migration file or updating database, we get exception at run time which says that your modeis changed but you haven’t added migration file.
 

So, to get rid from this exception, we need to add migration file to our project.

Before adding migration file, let’s once look over the migration folder inside solution explorer where you see that we have only intialcreate.cs file and configuration.cs file.

 

Now, open the “package manager console” from tool menu and run the following command :-

Cmd:- “add-migration AnyName”

For my project, I run the command :- “add-migration Rating”

 

After successfully adding migration a Rating.cs, the file automatically opens inside Visual Studio which shows the changes  we made inside our model class in the code.

Now, check the solution explorer, You find the Rating.cs file migration file added.


 

Now to update your LocalDB, run the command “update-database” inside package manger console.

Note:- Before running this command, don’t forget to add the rating value inside seed method because I told you earlier that at every update, database command internally runs the seed(). In this project, we are inserting data using seed method. So, first update seed() method by the following code, then run that command.
  1. protected override void Seed(CRUDDemo.Models.BookDBContext context)  
  2.   
  3. {  
  4.   
  5. context.BookLst.AddOrUpdate(p => p.Id, new BookModel  
  6.   
  7. {  
  8.   
  9. Id = 0,  
  10.   
  11. AuthorName = "Suryakant",  
  12.   
  13. BookName = "CRUD DEMO",  
  14.   
  15. PublishDate = new DateTime(2014, 09, 12),  
  16.   
  17. Rating=4  
  18.   
  19. }, new BookModel  
  20.   
  21. {  
  22.   
  23. Id = 1,  
  24.   
  25. AuthorName = "John",  
  26.   
  27. BookName = "Digital Life",  
  28.   
  29. PublishDate = new DateTime(2013, 10, 23),  
  30.   
  31. Rating=4  
  32.   
  33. });  
  34.   
  35. }
Now, run the update-database command. You see the seed method running  which shows in o/p of Package Manager console.


 
 
 Now, add the following line of code inside index.cshtml and run your project. You get the rating properties data inside the page.

<td>

@Html.DisplayFor(modelItem=>item.Rating)


  Now, you get the page with Rating as below:
 
That’s all about CRUD operation using Local DB with Data Migration. Hope you enjoyed reading this article.

Comment your query if anything is not working for you.

Thanks for reading.

You can download the whole Project from this link with complete functionality.