Code First Approach in Entity Framework
Introduction
What is Code First
Approach?
Entity
Framework is the Microsoft preferred method of data access for .NET
applications. It supports strongly-typed access through LINQ. Entity Framework
also allows developers to program against a conceptual model that reflects
application logic rather than a relational model that reflects the database
structure. Entity Framework can be used from an ASP.NET Application, (using
Entity Data Source) or in ASP.NET MVC etc. In this article we will be creating
this using MVC App and we’ll be using Visual Studio 2012 for
demo.
Code
First Approach provides an alternative to the Database First and Model First
approaches to the Entity Data Model and creates database of us based on our
classes that we will be creating in this article.
Demo MVC Application
Create
a new ASP.NET MVC Project by New > Project > ASP.NET MVC 4 Web
Application > Empty Template, you will get following structure.
Follow
the steps for the rest part of this demo.
Step 1: Adding NuGet
Package (if not available in references)
Right
Click on the References Folder and select 'Manage NuGet Packages'.
Alternatively you can install it from Tools > Library Package Manager >
Package Manager Console and type 'Install-Package EntityFramework'. Okay, let's
do this from NuGet Package window, type 'Entity Framework' in search box and click
to install it. After installation you will notice a new library file in
References Folder 'EntityFramework'.
Step 2: Adding Classes
Right
click on the Models Folder to add a new class file named 'Student.cs' and type
following codes.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Code_First_Approach_in_Entity_Framework.Models
{
public class Student
{
public int StudentID { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Mobile { get; set; }
}
}
So,
I have declared four properties: StudentID, Name, Address and Mobile. Now go
ahead and create a class to manage the link with the database above properties
by inheriting DbContext. Note to use a namespace System.Data.Entity.
Step 2: Adding DbContext
Right
click on the Models Folder to add a new class file named 'StudentContext.cs'
and type following codes.
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace Code_First_Approach_in_Entity_Framework.Models
{
public class StudentContext : DbContext
{
public DbSet<Student> Students { get; set; }
}
}
Now,
this DbContext will do lots of things for us like it will create database and tables.
You can check your newly added database file.
Step 3: Adding Controller
and Views
Build
the solution here by menu Build > Build Solution because I want Model class
and Data context class to be popped up for me in Add Controller window. Go
ahead to add a controller for this right click on the Controllers Folder in the
Solution Explorer and select Add > Controller and use the name
'StudentController' and make following selections as given in image below.
Now,
everything setup and ready for us including controller and its different views.
Let's run the project you will get error page as given below, this is because application is expecting 'Home' controller by default and we don't have this controller instead we have 'student' controller. You will see how to fix this in next step.
For
now request 'student' controller using url something like http://localhost:portnumber/student and try to perform CRUD operation.
Everything
is functioning well so far.
Step 4: Routing
Application
When
you run the application, you will get error page at very first hit, because the application
is expecting 'Home' as a controller by default but we don't have 'Home'
controller in our application instead we have 'Student' so we need to modify
the default hit by the application. For this, find a file 'RouteConfig.cs' in 'App_Start' folder and make a single change.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "student", action = "Index", id = UrlParameter.Optional }
);
Just
replaced the controller value to 'student'. Now run the application again, you
will not see that error page anymore.
If
you are interested to learn more on Routing, go ahead and learn it from
ScottGu's blog post here http://weblogs.asp.net/scottgu/archive/2007/11/13/asp-net-mvc-framework-part-1.aspx
or http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx.
Step 5: Data Validation
Using Data Annotations
Assume,
if you want to validate your data before sending it to database or you want to
define any validation expression or want to make any field as 'Required'. For
this we can take the advantage of 'System.ComponentModel.DataAnnotations.dll' assembly that is shipped with MVC package and you can find it in References
folder. Now to enable the validation, open 'Student.cs' model and add some
validation lines.
If
you run the application here, you will get error message.
Because,
this class file directly representing the database table's structure and making
any changes here is subject of 'Code First Migrations' to update database and
its tables and that why you got above error. Remember, you will lose all your
records if you migrate your database here. Still Microsoft is working on this subject to
avoid data lose, hoping to see such functionality in coming releases. Let's move to next step to do database migration.
If
you want to learn more on 'Data Validation Using Data Annotations', please read
here http://www.asp.net/mvc/tutorials/older-versions/models-(data)/validation-with-the-data-annotation-validators-cs.
Step 6: Database Migration
Now,
don't worry about data lose here and go ahead to update the database table to
test the above validation rules.
For
this, open Global.asax file and make following changes.
You
will notice above defined validations are working now, image give below.
If
you want to learn more on 'Code First Database Migration', please read here http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-code-based-migrations-walkthrough.aspx.
Step 8: Looking at
Database
So,
now if you want to see that where the database have been created for this app.
Open the directory where you have created your app and open App_Data folder you
will find you database files.
Now
the question is how to change the database instance name, this is soo long here. Let's learn it in
next step.
Step 7: Change Database
Name Instance
In
above image you can see our default database name that is 'Code_First_Approach_in_Entity_Framework.Models.StudentContext'. Let's change it. Remember you will again lose your records.
Open 'StudentContext.cs' file and make following changes.
Now,
again check back 'App_Data' folder, you will notice new database files have been created.
Download
the source code from here.
Find
a very nice video on this title by Julie Lerman here http://msdn.microsoft.com/en-us/data/gg715119.
I
have done couple of video posts on MVC basics, if you are interested go and
watch at my YouTube channel here http://www.youtube.com/user/abhimanyukumarvatsa.
Video Version of this post (in Hindi Language):-
Video Version of this post (in Hindi Language):-
I
hope you like this post. Thanks.
Good work man, this was simple, clear and good explanation of Entity framework i have came across.
ReplyDeleteBy any chance did you work on DB First approach.
Thanks
Thanks Patel.
DeleteYes I posted DB First title today http://www.itorian.com/2012/08/database-first-approach-in-entity.html.
Good work! Nice and precise!
ReplyDeleteTnx!
Thanks Abhimanyu..This tutorial is helpinglot.....
ReplyDeletedid you work on model first approach?
ReplyDeleteHi great tutorial thanks! I tried to follow it using Visual 2010 and MVC 3, I had the following problem "The provider did not return a ProviderManifestToken string" searching a solution I discovered I have no defined no connection string when I added one all works, I have no DB defined in AppData folder is this due to me using MVC 3 and not MVC 4 ?
ReplyDeletewhere is database connection string. How application read which database i can connect.
ReplyDeleteyou can always find it in web.config. EF connection string is bit different from normal db connection strings.
DeleteThanks @Abhimanyu
ReplyDeleteThanks Abhi,
ReplyDeleteThis is really simple to understand
Abhimanyu, this is really great to see your tutorial. I think you will go very long. Keep it up...
ReplyDeleteThanks Abhi,
ReplyDeleteLooking forward for more such stuff related to ASP.NET MVC.......
Thanks Abhimanyu,
ReplyDeleteReally a good article to understand the code first approch.Please suggest me that can we use this approach in a fresh NopCommerce application?
Hi Abhimanyu Sir,
ReplyDeleteHow it is possible when my class has some change and after migration of database then its table data should not be lost.
Every time you make changes in conceptual model (database model), use migration always to update database and safeguard your previous records.
DeleteThanks Abhimanyu,
ReplyDeleteIn my projects I use Code First to an Existing Database approach so the Code First creates a code based model that maps to an existing database using reverse engineering code first.
but I got stuck when I changed the database updating or adding some column and I don't know how to update my classes in the project.
Thank.
Hi Abhimanyu,
ReplyDeleteI am very new to MVC and like to learn. I have created the project as above. But when I click CreateNew it gives me this error:
CS0103: The name 'Scripts' does not exist in the current context
@Scripts.Render("~/bundles/jqueryval")
Can you please help?
Thank you
You need to add in View's web.config file like below
Delete<namespaces>
.....
<add namespace="System.Web.Optimization" />
.....
Thank you very much it is working.
DeleteHeloo sir I have Created Project as suggested by you. Project Works Fine
ReplyDeleteBut i am not able to see the database in the App_data folder in fact that folder it self is not available in the Project
What to do where to find the Database please help me !!!
hi,
DeleteIt will be visible to you once you will to the App_Data folder in your drive. Not through the Solution Explorer.
~ Regards,
Kush kant dayal | Pune
Database.SetInitializer(new DropCreateDatabaseIfModelChanges());
ReplyDeleteThe above code will drop the database when we change the model, instead of this approach use package manager console to enable Migrations
following code will enable the Migrations and update the database without loosing data.
PM> Enable-Migrations -ContextTypeName Code_First_Approach_in_Entity_Framework.Models.StudentContext
PM> Add-Migration Name
PM> update-database
Hi Abhimanyu sir, which approach is better according to u if we want to use entity framework?
ReplyDeleteHii , Abhi Sir ,
ReplyDeleteVery good post and it work very well and very well explained !! I have done migration by enabling the Migration in the Package Manager Console..
Can you tell me how to rename column in the Database using the Package manager Console ???
Waiting for your reply.GD !
thank you very much , that's so helpful , i'm a beginner in .NET and c# :D
ReplyDeleteIf you are going for finest contents like I do, simply pay
ReplyDeletea visit this site daily since it gives quality contents, thanks
My blog easy paycheck formula scam
hi
ReplyDeleteI had doubt is this code will effect in the local data base means we have inserted number of employees list is this reflect in local data base or not and i did this example but data base was not created in the local server
and my question is how to update this created Student
controller in the local database
Hi Abhimanyu,
ReplyDeleteIt's really very short,simple,quick and easy learning. Great stuff.
I have one issues while using this approach it getting error, "add-migration error: "model backing the context has changed" and "The model backing the ... context has changed since the database was created".
To short this problem out, I used the following line in my context class..
Database.SetInitializer(new DropCreateDatabaseIfModelChanges());
where my MyProjectDBContextClass is my ContextClass.
Now again it comes with another error..
"Additional information: Cannot drop database "CodeFirstDB" because it is currently in use."
Would you like to give any reply to me on that at [email protected] .
Thanks Avhi.
I am not able to add StudentController . it giving me error
ReplyDeleteunable to add StudentController..it give the following error
ReplyDeleteunable to retreive metadata for mvcapplication8.models.student..unable to cast of type 'system.Data.Entity.Objects.Objectcontext' to type 'System.Data.Objects.ObjectContext'
Sir if i do not Add Migration in project
ReplyDeleteGood article on Entity Framework Code first approach with example
ReplyDeleteThanks alot Abhimanyu Kumar Vatsa this article helps me alot..
ReplyDeleteThank you
ReplyDeleteHI,
ReplyDeletei don't now any thing in Mvc just Beginner code first approch connection string is needed or not ?
Thank you so much ♥
ReplyDelete