How to Use Code First Approach With Fluent API in ASP.NET MVC Application

Introduction

This article explains how to use the Code First Approach with the Fluent API in an ASP.NET MVC Application.

Step 1

Create a New MVC 4 Application and give it the name "Fluent API".

fluent api2.jpg

Now your new application will be ready for use. Now we need to add some Nuget to our application, so right-click on the name of your application in the Solution Explorer and choose to "Manage Nuget Package".

fluent api3.jpg

Step 2

In the Manage Nuget package Wizard search for "Entity Framework" and then click on the "Install" button to add this to your application. This will add assemblies to your project.

fluent api4.jpg

Now in the Solution Explorer right-click on the "Models" folder and choose to "Add a Class" and name it "FirstClass.cs". In this class you need to add the following code:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. namespace Fluent_API.Models  
  6. {  
  7.     public class Purchaser  
  8.     {  
  9.         public int PurchaserId { getset; }  
  10.         public string PurchaserName { getset; }  
  11.         public string MobileNo { getset; }  
  12.         public string City { getset; }  
  13.         public string District { getset; }  
  14.         public string State { getset; }  
  15.         public virtual ICollection<Requirement> Required { getset; }  
  16.     }  
  17.     public class Requirement  
  18.     {  
  19.         public int Id { getset; }  
  20.         public string Item { getset; }  
  21.         public int Quantity { getset; }  
  22.         public int UnitPrice { getset; }  
  23.         public int TotalPrice { getset; }  
  24.         public int? PurchaserId { getset; }  
  25.         public virtual Purchaser Purchaser { getset; }  
  26.     }  
  27. }  

Here we have provided two classes, one named "Purchaser" and the other named "Requirement". Both of these classes are inter-related to each other. In the Requirement class PurchaserId is the Foreign key.

Step 3

Now to allow the application to create the backup in the database, we need to provide the Connection String in the "Web.Config" file that will be like this:

  1. <connectionStrings>  
  2.     <add name="PurchaseConnectionString"  
  3.       connectionString="Data Source=MCNDESKTOP20;Initial Catalog=Purchased;User ID=sa;Password=*********"  
  4.       providerName="System.Data.SqlClient"/>  
  5. </connectionStrings>  

Here I first provided the name for the Connection String then I provided the name for the Database file that will be created in SQL.

Step 4

Now add a new class in the Models and name it "PurchaseClass.cs". In this class add the following code:  

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.ComponentModel.DataAnnotations.Schema;
  6. using System.Data.Entity;
  7. namespace Fluent_API.Models
  8. {
  9.     public class PurchaseClass : DbContext
  10.     {
  11.         public DbSet<Purchaser> Purchasers { getset; }
  12.         public DbSet<Requirement> Requirement { getset; }
  13.         public PurchaseClass():base("name=PurchaseConnectionString")
  14.         {
  15.         }
  16.         protected override void OnModelCreating(DbModelBuilder x)
  17.         {
  18.             x.Entity<Purchaser>().HasKey(c => c.PurchaserId);
  19.             x.Entity<Purchaser>().Property(c =>  c.PurchaserId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
  20.             x.Entity<Purchaser>().Property(c =>c.PurchaserName).HasMaxLength(80);
  21.             x.Entity<Purchaser>().Property(c => c.MobileNo).HasMaxLength(14);
  22.             x.Entity<Purchaser>().Property(c => c.City).HasMaxLength(40);
  23.             x.Entity<Purchaser>().Property(c => c.District).HasMaxLength(40);
  24.             x.Entity<Purchaser>().Property(c => c.State).HasMaxLength(20); 
  25.             x.Entity<Requirement>().HasKey(o => o.Id);
  26.             x.Entity<Requirement>().Property(o => o.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
  27.             x.Entity<Requirement>().Property(o => o.Item).HasMaxLength(50);
  28.             x.Entity<Requirement>().HasRequired(c => c.Purchaser)
  29.             .WithMany(o => o.Required).HasForeignKey(o => o.PurchaserId);
  30.             x.Entity<Requirement>()
  31.                 .HasRequired(c => c.Purchaser)
  32.                 .WithMany(o => o.Required)
  33.                 .HasForeignKey(o => o.PurchaserId)
  34.                 .WillCascadeOnDelete(true);
  35.             base.OnModelCreating(x);
  36.         }
  37.     }
  38. }

Here class "PurchaseClass" is inherited from the DbContext class, here the Connection String is called that was called in the Web.Config file. Until now the Fluent API is fully used.

Step 5

Now we will work on the Controllers. Add two Controllers in the Controllers Folder and name them "PurchaserController" and "RequirementController".

Now first open the "PurchaseController.cs" and add the following Actions Method to it:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using Fluent_API.Models;  
  7. namespace Fluent_API.Controllers  
  8. {  
  9.     public class PurchaserController : Controller  
  10.     {  
  11.         PurchaseClass purcls;  
  12.         public PurchaserController()  
  13.         {  
  14.             purcls = new PurchaseClass();  
  15.         }  
  16.         public ActionResult Index()  
  17.         {  
  18.             var Purchasers = purcls.Purchasers.ToList();  
  19.             return View(Purchasers);  
  20.         }  
  21.         public ActionResult Create()  
  22.         {  
  23.             var Purchaser = new Purchaser();  
  24.             return View(Purchaser);  
  25.         }  
  26.         [HttpPost]  
  27.         public ActionResult Create(Purchaser Pur)  
  28.         {  
  29.             purcls.Purchasers.Add(Pur);  
  30.             purcls.SaveChanges();  
  31.             return RedirectToAction("Index");  
  32.         }  
  33.         public ActionResult Delete(int id)  
  34.         {  
  35.             var Pur = purcls.Purchasers.Where(c => c.PurchaserId==id).First();  
  36.             return View(Pur);  
  37.         }  
  38.         [HttpPost]  
  39.         public ActionResult Delete(int id,Purchaser Pur)  
  40.         {  
  41.             var Purchaser = purcls.Purchasers.Where(c =>c.PurchaserId == id).First();  
  42.             if (Purchaser != null)  
  43.             {  
  44.                 purcls.Purchasers.Remove(Purchaser);  
  45.                 purcls.SaveChanges();  
  46.             }  
  47.             return RedirectToAction("Index");  
  48.         }  
  49.     }  
  50. }   

In the "RequirementController.cs" add the following Action Method:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using Fluent_API.Models;  
  7. namespace Fluent_API.Controllers  
  8. {  
  9.     public class RequirementController: Controller  
  10.     {  
  11.         PurchaseClass purcls;  
  12.         public RequirementController()  
  13.         {  
  14.             purcls = new PurchaseClass();  
  15.         }  
  16.         public ActionResult Index()  
  17.         {  
  18.             var Requirement = purcls.Requirement.ToList();  
  19.             return View(Requirement);  
  20.         }  
  21.         public ActionResult Create()  
  22.         {  
  23.             var Requirement = new Requirement();  
  24.             return View(Requirement);  
  25.         }  
  26.         [HttpPost]  
  27.         public ActionResult Create(Requirement Req)  
  28.         {  
  29.             purcls.Requirement.Add(Req);  
  30.             purcls.SaveChanges();  
  31.             return RedirectToAction("Index");  
  32.         }  
  33.         public ActionResult Delete(int id)  
  34.         {  
  35.             var Requirement = purcls.Requirement.Where(o => o.Id == id).First();  
  36.             return View(Requirement);  
  37.         }  
  38.         [HttpPost]  
  39.         public ActionResult Delete(int id, Requirement Req)  
  40.         {  
  41.             var Requirement = purcls.Requirement.Where(o => o.Id == id).First();  
  42.             if (Requirement != null)  
  43.             {  
  44.                 purcls.Requirement.Remove(Requirement);  
  45.                 purcls.SaveChanges();  
  46.             }  
  47.             return RedirectToAction("Index");  
  48.         }  
  49.     }  
  50. }   

Step 6

The final step is to Add the Views for both the Purchaser and the Requirement. For this first add two separate folders in the views and name them "Purchaser" and "Requirement", then add three views in both of these folders named "Index", "Create" and "Delete". These views will allow you to see and utilize your application. You can add the code to these views by downloading the downloadable file that I provided at the start of the project.

On running the application and navigating to the Index View you will get the output like this:

fluent api6.jpg

At first, nothing will be available in the Purchaser List, so click on Create New to Add a New Purchaser.

Now provide the specifications for this Purchaser and then click on the Create Button.

fluent api7.jpg

Now you will see that this Purchaser's Entry is shown in the output window.

fluent api8.jpg

Step 7

Now if you go to your SQL and check there then you will find that a new database named "Purchased" is created in your database and the entry that you provided is also available under the "Purchaser" table.

fluent api9.jpg


Similar Articles