This article describes how to create a ASP.NET MVC Application Using Entity Framework Code First Model development approach. To start we need some predefined basic knowledge about ASP.NET MVC. Summery of the article:
- What is Code First Model?
- Database Design
- Project Creation
- Adding a Connection String
- Adding a Database Model
- Adding a Context Class
- Adding a Controller
- Adding Views
- Create Navigation
- Run the Application
- Common Errors in ASP.NET MVC
What is Code First Model?
In Code First approach we avoid working with the Visual Designer of Entity Framework. We can say, the EDMX file is excluded from the solution. So now, we have complete control over the context class as well as the entity classes.
Database Design
Create a Database in your SQL Server named TestDB. Create a Students table in the database. The SQL scripts for Students table:
CREATE TABLE [dbo].[Students]( [StudentID] [int] IDENTITY(1,1) NOT NULL, [StudentName] [nvarchar](150) NULL, [Address] [nvarchar](200) NULL, [Phone] [nvarchar](50) NULL, CONSTRAINT [PK_member] PRIMARY KEY CLUSTERED ( [StudentID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]
Project Creation
Create a ASP.NET MVC Project. The steps to Create a ASP.NET MVC Project:
Step-1
If you have Microsoft Visual Studio installed, Start it and select New Project form the file menu.
- In the New Project dialog box:
- Open the Visual C# templates
- Select the template ASP.NET MVC 2 Web Application
- Set the project name to MvcFirstApp
- Set the disk location to something like C:\TestProject
- Click OK
Step-2
A window will be open for unit test. If you want to create a unit test project select yes. Other wise select No and click ok.
Step-3
Visual Studio will create a project like this:
Adding a Connection String
we need to add or create a connection string in Web.config file.Add the following element to the <connectionStrings> element in Web.config file:
<add name="MovieDBContext" connectionString="Data Source=(localhost);Initial Catalog=TestDB;Persist Security Info=True;User ID=sa;Password=sa123" providerName="System.Data.SqlServerCe.4.0"/>
Adding a Database Model
We need to create a database model.
- In the Solution Explorer, right-click the Models folder, and select Add and Class
- Name the class StudentModels.cs and click Add
- Edit the class as like:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; using System.ComponentModel.DataAnnotations; namespace MvcStudent.Models { public class Students { [Key] public int StudentID { get; set; } [Required] public string StudentName { get; set; } public string Address { get; set; } public string Phone { get; set; } } }
Class name should as like our table name. In our Students table we have StudentID, StudentName, Address, Phone field. StudentID is integer and others fields are varchar type.
In our table StudentID is primary key. That’s why have used [Key] to clarify that it is the Primary Key. If the field name is “ID” then we don’t need to use [Key]. [Required] is used for required filed validation. That means StudentName is mandatory.
The following namespace or reference is required for ASP.NET MVC Application Using Code First Model.
System.Data.Entity;
System.ComponentModel.DataAnnotations;
Adding a Context Class
DbContext is a built class of .Net. DbContext is a lightweight version of the ObjectContext class. DbContext requires a lot less code for the same kind of functionality. ObjectContext EF V4.0 and DbContext EF V4.1
We need to create a Context class in our data model.
In the Solution Explorer, right-click the Models folder, and select Add and Class.
Name the class DBContext.cs and click Add.
Edit the class as like:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; using MvcStudent.Models; namespace MvcStudent.Models { public class DBContext:DbContext { public DbSet Students { get; set; } } }
Adding a Controller
We need to create a Controller for the Student. We can create a Controller by following steps:
- Re-Build the project from the menu
- In the Solution Explorer, right-click the Controllers folder, and select Add and Controller
- Set controller name to StudentController
- Select template: Controller with read/write actions and views, using Entity Framework
- Select model class: Students (MvcDemo.Models)
- Select data context class: DBContext (MvcDemo.Models)
- Select views : ASPX(C#)
- Click Add
Visual Studio will create the following files:
- A StudentController.cs file in the Controllers folder
- A Student folder in the Views folder
Adding Views
Visual Studio will automatically create the following files in the Student folder:
- Create. aspx
- Delete. aspx
- Details. aspx
- Edit. aspx
- Index. aspx
Create Navigation
Create navigation in Site.Master for Student.
We can do it by using the ActionLink method. Here is a sample code that navigates the “Student” controller and invokes the Index action.
<%: Html.ActionLink(“Student”, “Index”, “Student”) %>
Our Site.Master page will be like:
<ul id="menu"> <li><%: Html.ActionLink("Home", "Index", "Home") %></li> <li><%: Html.ActionLink("About", "About", "Home") %></li> <li><%: Html.ActionLink("Student", "Index", "Student") %></li> </ul>
Run the Application
Select Debug, Start Debugging (or F5) from the Visual Web Developer menu.
Our application will look like:
Common Errors in ASP.NET MVC
In any ASP.NET MVC Application we can face the following errors:
That’s all about Database Application in ASP.NET MVC
Good example for Code First Model.
But can you prove an example for EF
Thanks.