This article discusses a very simple manner to do the CRUD operation using LocalDB with entity framework and how to use code first Database migration.

So, after reading this article you are going to know about;

  • Uses and purpose of LocalDb.
  • Connection string about LocalDb.
  • Model Binding.
  • What is DBContext class ?
  • Step by step description of CRUD operation using LocalDb with Entity Framework.
  • What is Data Migration?
  • How to Do Migration using in code first approach.

Note: Before we start if you are new to MVC and you want complete project as reference then click download link to download complete project.

What is LocalDb and where it Exist ?

In general LocalDb is very similar to our Sql Server.

But LocalDb has some Limited feature then Sql Server.LocalDb only found inside Visual studio.

By default Visual studio provide one local Server and local database in the development phase.

Local server is called as IIS Express and local database is LocalDB. So both these two are pre-installed inside visual studio and helps the developer to continue development process although Local IIS and Sql server stopped providing services.

Note: If you change the setting of the project that to run the project using LocalIS then VisualStudio show you a pop-up window as given bellow,


Click on No. If you click on yes then configuration set for Local IIS.

This is basic concept about Local DB and purpose; as we go into deeper of this article we see where LocalDB exist and how to access it, so to see this live

Let’s start Visual studio to see the concept in live,

Open VisualStudio. (I am using VS2013)

Select New project from file menu,


Then give the project name as “CRUDDemo”


Select ASP.Net Web Application then select MVC template to create project; after successfully created your project then go to solution explorer and check whether LocalDB available inside App_Data folder or not. Because as I told LocalDB by default location is App_Data.

You cannot find any thing inside App_Data.The data which present under App_Data folder is always is in hidden format so click on show all file like bellow.

App_Data folder

So as we see also we click on show all file we won’t find any file inside App_Data folder.

So let’s start creating controller class and model to get the DBFile.

Add a controller called as BookController as follows,



Chose empty controller and click on add.


Now you get the BookController class is created.

Inside BookController you get a default action method called as Index().

Now what we do ?

These are our objective to implement inside this project.

Objective 1 - Our first objective is to shows list of Book Details inside index page using LocalDb and EntityFramework

To do this follow bellow step,

Step 1 - Add class for BookModel which contain all the property for book details. So go to model folder and right click over it and go to add and click on class.

Add class

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


Then you got BookModel class ; then add bellow code inside the model,

01.using System;
02.using System.Collections.Generic;
03.using System.Data.Entity;
04.using System.Linq;
05.using System.Web;
07.namespace CRUDDemo.Models
09.    public class BookModel
10.    {
11.public int Id { get; set; }
12.        public string BookName { get; set; }
13.        public string AuthorName { get; set; }
15.        public DateTime PublishDate { get; set; }
16.    }
17.    //BookDBContext inherited form DBContext Class.
18.    //This Class helps us to work with LocalDatabase.
19.    //Remember the localDB connnectiostring by deuflt congigured with application once you created the DBContext Class.
21.    public class BookDBContext : DbContext
22.    {
23.        public DbSet<BookModel> BookLst { get; set; }
24.    }

In the above code we see that there are two class one is called BookModel.cs which represent as model for our CRUD operation and one more class we have that is 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’s allows us to access all the method of Dbcontext class.

DbContext class is specially designed for to work with DB operation using Codefirst approach.

Note: Here We inherited BookDBContext class Explicilty form 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 going to return list of Book.

Now Build your project -> Ctrl+shift+B

After build succeed add the bellow code inside BookController action method index().

01.using System;
02.using System.Collections.Generic;
03.using System.Linq;
04.using System.Web;
05.using System.Web.Mvc;
06.using CRUDDemo.Models;
07.namespace CRUDDemo.Controllers
09.    public class BookController : Controller
10.    {
11.        private BookDBContext objBookDb = new BookDBContext();
12.        // GET: /Book/
13.        public ActionResult Index()
14.        {
15.            return View(objBookDb.BookLst.ToList());
16.        }
17.    }

In the above code we have create BookDBConetext object called as objBookDb; which helps us to provide different operation using it’s property. In return view we are sending list of Book to our view to see all the book.

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

2.                name: "Default",
3.                url: "{controller}/{action}/{id}",
4.                defaults: new { controller = "Book", action = "Index", id = UrlParameter.Optional }
5.            );

Now if we directly run the application without adding view also we can get our LocalDB inside AppData folder; before run the application first check once if the LocalDB is exist or not.

You found there is no LocalDB exist but once you run the application you can find LocalDB file inside AppData folder.

Once your app run due to view not exist you get the exception that view not found. Close the browser and comes to visualstudio and check the LocalDB file with your DBContext class name is created as bellow.

app data

Note: If you won’t find this file then click on show all option in solutuion explorer as shown above.

Now we go to create a view page for Index action method which show us List of Book.

To create view : Right click inside Index action method and click on add view then you get a template which ask to bind your model and add scaffolding template as show bellow,

app data


Inside Template select “List” and 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,


To Insert the data into local DB 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 telling later because here we can understand what is DB Migration ?

We all generally know we have two types of method to insert the data; first one using web page and second one is to open SQL Server and write the Sql Query to insert the data.

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

Don’t confuse about seed() method we see the live example how seed method is working when we do migration.

Let’s first Understand what is Migration and why we required migration ?

Migration is a technique which helps us to enable auto update to our DB while we are working with entity framework. In simple if we change any thing inside our model class and we want that same thing to be refelect inside our DB then we 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 following cmd :- “enable-migrations -ContextTypeName


Package Manger Console

After run you get bellow output,


After succefully enable migration then we find one migration folder added inside solution and that migration folder contain two file first one is IntialCreate.cs and other one is Configuration.cs.


InitalCreate.cs file is the design view of our Model which going to map the Database; where as Configuration.cs file plays an important role while working with migration.

It contain a sealed class inherited from “DBMigrationConfiguration” class. This class contain the seed() method which I mention earlier.

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

In 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 by following code.

01.protected override void Seed(CRUDDemo.Models.BookDBContext context)
02.        {
03.            context.BookLst.AddOrUpdate(p => p.Id, new BookModel
04.            {
05.                Id = 0,
06.                AuthorName = "Suryakant",
07.                BookName = "CRUD DEMO",
08.                PublishDate = new DateTime(2014, 09, 12)
09.            }, new BookModel
10.            {
11.                Id = 1,
12.                AuthorName = "John",
13.                BookName = "Digital Life",
14.                PublishDate = new DateTime(2013, 10, 23)
15.            });
17.        }

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 seed method is running.


After this run your project you find two record showing inside the page which we writeen under seed().


This is how we insert data to Database.

Now let’s do CRUD operation,

We already did Creation part using Seed(); I am skiping to CreateNew page and add a new record. I am directly Inserting data using Seed().

Now we update the record using Edit Link.

To do this follow bellow step,

Add Action method called as Edit as bellow,

01.public class BookController : Controller
02.    {
03.        private BookDBContext objBookDb = new BookDBContext();
04.        // GET: /Book/
05.        public ActionResult Index()
06.        {
07.            return View(objBookDb.BookLst.ToList());
08.        }
09.        //GET:/Edit/
10.        public ActionResult Edit(int? id)
11.        {
12.            if (id == null)
13.            {
14.                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
15.            }
16.            var model = objBookDb.BookLst.Find(id);
17.            if (model == null)
18.            {
19.                return HttpNotFound();
20.            }
21.            return View(model);
22.        }
Then add a view for this action method.

Here I am using scaffolding to add the view; right click inside action method and follow bellow screen shot.

add a view

add a view

Now select your Model class then click on add Button.

You will get a nicely designed view.

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


When you click on Save button we need to save it inside Database.

For save data we write another method using HttpPost attribute and give same name as edit.

Write bellow code for Save Data.

02.        [HttpPost]
03.        public ActionResult Edit(BookModel model)
04.        {
05.            if (ModelState.IsValid)
06.            {
07.                objBookDb.Entry(model).State = EntityState.Modified;
08.                objBookDb.SaveChanges();
09.                return RedirectToAction("Index");
11.            }
12.            else
13.                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
14.        }

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 Visualstudio.

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

Now last operation we need to do Delete data.

To do this add the following code,

03.        public ActionResult Delete(int id)
04.        {
05.            var model = objBookDb.BookLst.Find(id);
06.            if (model == null)
07.            {
08.                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
09.            }
10.            objBookDb.BookLst.Remove(model);
11.            objBookDb.SaveChanges();
12.            return RedirectToAction("Index");
13.        }

Now run your app and click on delete button then your record deleted.

Now we see the last concept how to add migration file inside our project :-

Before we see the it live example first we need to understand why we need to add migration to our project or when I need to add migration file to our project ?

The purpose of generating migration file is to make update our local Database when anything changed inside our model claas.

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

Let see the concept in Live :-

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

01.public class BookModel
02.    {
03.        public int Id { get; set; }
04.        public string BookName { get; set; }
05.        public string AuthorName { get; set; }
07.        public DateTime PublishDate { get; set; }
08.        public int Rating { get; set; }
09.    }

Now build your project.

If we run now our project without adding migration file or updating database we get exception at run time which say that your model changed but you won’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 we have only one 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 successful adding migration a Rating.cs file automatically open inside visual studio which show the changes which 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 run this command don’t forget that to add the rating value inside seed method because I told you earlier that at every update database command internally run the seed(). In this project we are inserting data using seed method. So first update seed() method by following code then run that command.

01.protected override void Seed(CRUDDemo.Models.BookDBContext context)
02.        {
03.            context.BookLst.AddOrUpdate(p => p.Id, new BookModel
04.            {
05.                Id = 0,
06.                AuthorName = "Suryakant",
07.                BookName = "CRUD DEMO",
08.                PublishDate = new DateTime(2014, 09, 12),
09.                Rating=4
10.            }, new BookModel
11.            {
12.                Id = 1,
13.                AuthorName = "John",
14.                BookName = "Digital Life",
15.                PublishDate = new DateTime(2013, 10, 23),
16.                Rating=4
17.            });
19.        }

Now run the update-database command you see the seed method run which show 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.




  Now you get the page with Rating as bellow;


That’s all about CRUD operation using Local DB with Data Migration.


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