Code-First Approach With ASP.NET MVC Framework

Introduction

 
In this article, we’ll learn how to perform CRUD operations with a code-first approach in an MVC application. Here, we will create an MVC structure that will help to change in the Model Class, and that change will update in the database. Microsoft’s Entity Framework (EF) avoids working directly with the database and creates the database as per model classes. We will not use a visual model designer (EDMX) completely but will create POCO classes first and then create the database from these POCO classes.
 
Recommended Prerequisites
  • Visual Studio 2010 SP1
  • ASP.NET MVC
  • SQL Server
Step 1
 
Open Visual Studio and select “File” >> "New". Then click on Project. (Remember, don't go with the option 'File->New->Website'.)
 
ASP.NET
 
Step 2
 
Select “Templates” >> Visual C# >> Web then ASP.NET Web Application (.NET Framework), and put appropriate project name.
  • And click the “OK” button. 
ASP.NET
 
Step 3
 
And, here is your default screen.
 
ASP.NET
 
Here, we will create the basic structure which looks professional and easy to use.
  1. Code-First-Demo
     
    It contains Web UI like our Controller, Views, JS, Custom models, etc.
     
  2. Code-First-Demo.Repository
     
    It contains our migration files (whatever file we have generated in the application, it will be added to this project).
     
  3. Code-First-Demo.Model
     
    It contains our Model classes. (whatever classes/models we have generated in the application, they will be added to this project).
Step 4
 
Right click on Solution >> Add >> New Project.
 
ASP.NET 
 
Now, we will add our Code-First-Demo.Repository Class Library which contains our Migration files.
 
ASP.NET 
 
After adding the project, delete the default class namely Class1.cs.
 
Step 5
 
Right-click on Code-First-Demo.Repository >> Add and add a new class.
 
ASP.NET 
 
Step 6
 
Click on the class and give an appropriate name. Here, I’ll set the name as CDBContext.
 
ASP.NET 
 
Step 7
 
Now, add the reference of EntityFramework, add namespace "using System.Data.Entity;" and set access specifier as public and extend from DbContext.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data.Entity;  
  4. using System.Linq;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace Code_First_Demo.Repository  
  9. {  
  10.     public class CDBContext : DbContext  
  11.     {  
  12.     }  
  13. }  
 Now, add your connction string in Web.config file of the Main (Code-First-Demo) Project.
  1. <connectionStrings>  
  2.   <add name="StringDBContext" connectionString="Server=FAISAL-PATHAN\SQLEXPRESS;Initial Catalog=DemoDB;Persist Security Info=False;User ID=sa;Password=***;MultipleActiveResultSets=True;Encrypt=False;TrustServerCertificate=False;Connection Timeout=30;" providerName="System.Data.SqlClient" />  
  3. </connectionStrings>  
ASP.NET 
 
Step 8
 
Create constructor and extend from the base class and pass connectionstring name which we set in web.config file.
 
ASP.NET 
 
Step 9
 
Right-click on Solution, add a new project.
 
ASP.NET 
 
Now, we will add our Code-First-Demo.Model Class Library, which contains all our classes.
 
ASP.NET 
 
After this, delete the default class namely Class1.cs.
 
Now, we must add Code-First-Demo.Model Class Library reference to Code-First-Demo.Repository Class Library in order to access and generate a table in SQL Server. 
 
Step 10
 
Add Code-First-Demo.Model Class Library reference to Code-First-Demo.Repository Class Library. Right-click on Code-First-Demo.Repository, Select Add > Reference.
 
ASP.NET
 
Now, select Code-First-Demo.Model and click OK.
 
ASP.NET 
 
In Code-First-Demo.Repository Class library, you can see Code-First-Demo.Model reference.
 
Step 11
 
Now, we are adding our class to Code-First-Demo.Model to create our SQL table.
 
ASP.NET 
Step 12
 
Add properties to the class as per columns that you want in the table.
  1. Add reference System.ComponentModel.DataAnnotations.dll to Code_First_Demo.Models.
  2. Set the Key attribute to your primary key.
     
    1. The Key attribute can be applied to a property in an entity class to make it a key property and the corresponding column to a PrimaryKey column in the database.
       
  3. Add using System.ComponentModel.DataAnnotations; namespace.
ASP.NET 
 
MyFirstTable.cs class
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.Linq;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace Code_First_Demo.Models  
  9. {  
  10.     public class MyFirstTable  
  11.     {  
  12.         [Key]  
  13.         public int ID { getset; }  
  14.         public string Name { getset; }  
  15.         public int Age { getset; }  
  16.     }  
  17. }  
Step 13 - Add DbSet Properties
 
Add using Code_First_Demo.Models; namespace.
 
ASP.NET 
 
CDBContext.cs
 
  1. using Code_First_Demo.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Data.Entity;  
  5. using System.Linq;  
  6. using System.Text;  
  7. using System.Threading.Tasks;  
  8.   
  9. namespace Code_First_Demo.Repository  
  10. {  
  11.     public class CDBContext : DbContext  
  12.     {  
  13.         public CDBContext() : base("StringDBContext")  
  14.         {  
  15.         }  
  16.         public DbSet<MyFirstTable> MyFirstTable { getset; }  
  17.     }  
  18. }  
Step 14
 
Now, open the package manager console to fire the commands.
 
ASP.NET 
 
Enable-Migrations
 
Enables Code First Migrations in the project.
 
Syntax
  1. Enable-Migrations [-ContextTypeName <String>][-EnableAutomaticMigrations][-MigrationsDirectory <String>]  
  2. [-ProjectName <String>][-StartUpProjectName <String>][-ContextProjectName <String>][-ConnectionStringName <String>]  
  3. [-Force][-ContextAssemblyName <String>][-AppDomainBaseDirectory <String>][<CommonParameters>]  
  4. Enable-Migrations [-ContextTypeName <String>][-EnableAutomaticMigrations][-MigrationsDirectory <String>]  
  5. [-ProjectName <String>][-StartUpProjectName <String>][-ContextProjectName <String>] -ConnectionString <String>   
  6. -ConnectionProviderName <String> [-Force][-ContextAssemblyName <String>][-AppDomainBaseDirectory <String>]  
  7. [<CommonParameters>]   
Add-Migration
 
Scaffold a migration script for any pending model changes.
 
Syntax
  1. Add-Migration [-Name] <String> [-Force][-ProjectName <String>][-StartUpProjectName <String>]  
  2. [-ConfigurationTypeName <String>][-ConnectionStringName <String>][-IgnoreChanges]  
  3. [-AppDomainBaseDirectory <String>][<CommonParameters>]  
  4. Add-Migration [-Name] <String> [-Force][-ProjectName <String>][-StartUpProjectName <String>]  
  5. [-ConfigurationTypeName <String>] -ConnectionString <String> -ConnectionProviderName <String>   
  6. [-IgnoreChanges][-AppDomainBaseDirectory <String>][<CommonParameters>]  
Update-Database
 
Apply any pending migrations to the database.
Syntax
  1. Update-Database [-SourceMigration <String>][-TargetMigration <String>][-Script][-Force][-ProjectName <String>]  
  2. [-StartUpProjectName <String>][-ConfigurationTypeName <String>][-ConnectionStringName <String>][-AppDomainBaseDirectory <String>]  
  3. [<CommonParameters>]  
  4. Update-Database [-SourceMigration <String>][-TargetMigration <String>][-Script][-Force][-ProjectName <String>]  
  5. [-StartUpProjectName <String>][-ConfigurationTypeName <String>] -ConnectionString <String> -ConnectionProviderName <String>   
  6. [-AppDomainBaseDirectory <String>][<CommonParameters>]  
Type/Select below commands and press enter key.It will added EntiryFramwork releted packages.
 
Install-Package EntityFramework 
 
ASP.NET
 
Enable-Migrations 
 
ASP.NET 
 
Add-Migration MyMigration 
 
Note: You can put any migration name as per your choice.
 
ASP.NET
 
This command will create your migration file based on the model's properties.
 
Update-Database
 
Note: This command will Create/modify your database on the mention connectionstring in the web.config file
 
ASP.NET 
 
ASP.NET
 
Step 15
 
Now Rebuild the solution and Perform the below action to do CRUD operations.
 
Add a reference to both class library projects to the main web project. 
 
ASP.NET
 
ASP.NET 
 
Step 16
 
Now Add New Controller for CRUD operation.
 
Right-click on Controllers, Add, and Controller...
 
ASP.NET 
 
Select "MVC 5 controller with views, using entity framework." and click on the Add button.
ASP.NET
  • Select your model and context class and set Controller name, (Don't remove Controller suffix),
  • Click on the Add button to create a controller and its views.
ASP.NET
 
ASP.NET 
 
Here we dis the Code-First approach in MVC application in an easy way.
 
Output
 
Create Page
 
ASP.NET
 
Display Page (List of Users)
 
ASP.NET 
 
Edit Page 
 
ASP.NET 
 
Delete Page
 
ASP.NET
 

Summary

 
Here, we created a simple application that uses the Entity Framework and SQL Server to perform CRUD operations with a Code First approach. In the following article, we will see how to do basic CRUD operations. You can leave feedback/comments/questions to this article. Please let me know how you like and understand this article and how I could improve it. 


Recommended Free Ebook
Similar Articles