DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • What Is SQL Injection and How Can It Be Avoided?
  • Non-blocking Database Migrations
  • Introduction to Data Replication With MariaDB Using Docker Containers
  • Working With dotConnect for SQL Server in ASP.NET Core

Trending

  • Event-Driven Architectures: Designing Scalable and Resilient Cloud Solutions
  • Chat With Your Knowledge Base: A Hands-On Java and LangChain4j Guide
  • Debugging With Confidence in the Age of Observability-First Systems
  • AI Speaks for the World... But Whose Humanity Does It Learn From?
  1. DZone
  2. Data Engineering
  3. Databases
  4. Code-First Approach With ASP.NET MVC Framework

Code-First Approach With ASP.NET MVC Framework

We create a simple application that uses the Entity Framework and a SQL Server to perform CRUD operations with a Code First approach.

By 
Faisal Pathan user avatar
Faisal Pathan
·
Updated Jul. 11, 18 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
35.0K Views

Join the DZone community and get the full member experience.

Join For Free

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 it in the database. Microsoft’s Entity Framework (EF) avoids working directly with the database and creates the database per the model classes' requirements. We will not use 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 give it an 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 UIs, 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 named Class1.cs.

Step 5

Right-click on Code-First-Demo.Repository >> Add, and add a new class.

ASP.NET

Step 6

Click on class and give it an appropriate name. Here, I’ll set the name to 'CDBContext.'

ASP.NET

Step 7

Now, add a reference to EntityFramework, add the namespace "using System.Data.Entity," set the access specifier to public, and extend from DbContext.

using System;  
using System.Collections.Generic;  
using System.Data.Entity;  
using System.Linq;  
using System.Text;  
using System.Threading.Tasks;  

namespace Code_First_Demo.Repository  
{  
    public class CDBContext : DbContext  
    {  
    }  
}  

 Now, add your connection string in the Web.config file of the main (Code-First-Demo) project.

<connectionStrings>  
  <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" />  
</connectionStrings>  

ASP.NETStep 8

Create a constructor, extend it from the base class, and pass it in.

ASP.NET

Step 9

Right click on Solution, and add a new project.

ASP.NET

Now, we will add our Code-First-Demo.Model class library, which contains all our classes.

ASP.NETAfter this, delete the default class named Class1.cs.

Now, we must add a Code-First-Demo.Model class library reference to Code-First-Demo.Repository class library in order to access and generate a table in our SQL Server. 

Step 10

Add a 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 a 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 the columns 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 a namespace using System.ComponentModel.DataAnnotations.

ASP.NET

MyFirstTable.cs class

using System;  
using System.Collections.Generic;  
using System.ComponentModel.DataAnnotations;  
using System.Linq;  
using System.Text;  
using System.Threading.Tasks;  

namespace Code_First_Demo.Models  
{  
    public class MyFirstTable  
    {  
        [Key]  
        public int ID { get; set; }  
        public string Name { get; set; }  
        public int Age { get; set; }  
    }  
}  

Step 13 - Add DbSet Properties

Add a namespace using Code_First_Demo.Models.

ASP.NET CDBContext.cs 

using Code_First_Demo.Models;  
using System;  
using System.Collections.Generic;  
using System.Data.Entity;  
using System.Linq;  
using System.Text;  
using System.Threading.Tasks;  

namespace Code_First_Demo.Repository  
{  
    public class CDBContext : DbContext  
    {  
        public CDBContext() : base("StringDBContext")  
        {  
        }  
        public DbSet<MyFirstTable> MyFirstTable { get; set; }  
    }  
}  

Step 14

Now, open the package manager console to fire the commands.

ASP.NETEnable-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 the below commands and press enter:

Install-Package EntityFramework

This will add EntiryFramwork related packages.

ASP.NET

Enable-Migrations 

ASP.NET

Add-Migration MyMigration 

Note: You can put any migration name you choose.

ASP.NET

This command will create your migration file based on model's properties.

Update-Database

Note: This command will Create/modify your database when a connection string is mentioned in the web.config file.

ASP.NET 

ASP.NET

Step 15

Now rebuild the solution and perform the below action to perform CRUD operations.

Add a reference to both the class library projects to the main web project. 

ASP.NET 

ASP.NET

Step 16

Now add a new controller for CRUD operations.

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 the Controller name (don't remove the Controller suffix).

  • Click on the Add button to create a controller and its views.

ASP.NET 

ASP.NET

Here we did 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 a 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. 

  • GitHub URL
ASP.NET MVC ASP.NET Database Framework Web application sql Library

Published at DZone with permission of Faisal Pathan. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • What Is SQL Injection and How Can It Be Avoided?
  • Non-blocking Database Migrations
  • Introduction to Data Replication With MariaDB Using Docker Containers
  • Working With dotConnect for SQL Server in ASP.NET Core

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: