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".
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".
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.
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:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Fluent_API.Models
{
public class Purchaser
{
public int PurchaserId { get; set; }
public string PurchaserName { get; set; }
public string MobileNo { get; set; }
public string City { get; set; }
public string District { get; set; }
public string State { get; set; }
public virtual ICollection<Requirement> Required { get; set; }
}
public class Requirement
{
public int Id { get; set; }
public string Item { get; set; }
public int Quantity { get; set; }
public int UnitPrice { get; set; }
public int TotalPrice { get; set; }
public int? PurchaserId { get; set; }
public virtual Purchaser Purchaser { get; set; }
}
}
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:
<connectionStrings>
<add
name="PurchaseConnectionString"
connectionString="Data Source=MCNDESKTOP20;Initial Catalog=Purchased;User ID=sa;Password=*********"
providerName="System.Data.SqlClient"/>
</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:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
namespace Fluent_API.Models
{
public class PurchaseClass : DbContext
{
public DbSet<Purchaser> Purchasers { get; set; }
public DbSet<Requirement> Requirement { get; set; }
public PurchaseClass()
:base("name=PurchaseConnectionString")
{
}
protected override void OnModelCreating(DbModelBuilder x)
{
x.Entity<Purchaser>().HasKey(c => c.PurchaserId);
x.Entity<Purchaser>().Property(c => c.PurchaserId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
x.Entity<Purchaser>().Property(c =>
c.PurchaserName).HasMaxLength(80);
x.Entity<Purchaser>().Property(c =>
c.MobileNo).HasMaxLength(14);
x.Entity<Purchaser>().Property(c => c.City).HasMaxLength(40);
x.Entity<Purchaser>().Property(c =>
c.District).HasMaxLength(40);
x.Entity<Purchaser>().Property(c => c.State).HasMaxLength(20);
x.Entity<Requirement>().HasKey(o => o.Id);
x.Entity<Requirement>().Property(o =>
o.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
x.Entity<Requirement>().Property(o =>
o.Item).HasMaxLength(50);
x.Entity<Requirement>().HasRequired(c => c.Purchaser)
.WithMany(o => o.Required).HasForeignKey(o => o.PurchaserId);
x.Entity<Requirement>()
.HasRequired(c => c.Purchaser)
.WithMany(o => o.Required)
.HasForeignKey(o => o.PurchaserId)
.WillCascadeOnDelete(true);
base.OnModelCreating(x);
}
}
}
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:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Fluent_API.Models;
namespace Fluent_API.Controllers
{
public class PurchaserController : Controller
{
PurchaseClass purcls;
public PurchaserController()
{
purcls = new PurchaseClass();
}
public ActionResult Index()
{
var Purchasers = purcls.Purchasers.ToList();
return View(Purchasers);
}
public ActionResult Create()
{
var Purchaser = new Purchaser();
return View(Purchaser);
}
[HttpPost]
public ActionResult Create(Purchaser Pur)
{
purcls.Purchasers.Add(Pur);
purcls.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult Delete(int id)
{
var Pur = purcls.Purchasers.Where(c => c.PurchaserId==id).First();
return View(Pur);
}
[HttpPost]
public ActionResult Delete(int id,Purchaser Pur)
{
var Purchaser = purcls.Purchasers.Where(c =>
c.PurchaserId == id).First();
if (Purchaser != null)
{
purcls.Purchasers.Remove(Purchaser);
purcls.SaveChanges();
}
return RedirectToAction("Index");
}
}
}
In the "RequirementController.cs" add the following Action Method:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Fluent_API.Models;
namespace Fluent_API.Controllers
{
public class RequirementController : Controller
{
PurchaseClass purcls;
public RequirementController()
{
purcls = new PurchaseClass();
}
public ActionResult Index()
{
var Requirement = purcls.Requirement.ToList();
return View(Requirement);
}
public ActionResult Create()
{
var Requirement = new Requirement();
return View(Requirement);
}
[HttpPost]
public ActionResult Create(Requirement Req)
{
purcls.Requirement.Add(Req);
purcls.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult Delete(int id)
{
var Requirement = purcls.Requirement.Where(o=>o.Id==id).First();
return View(Requirement);
}
[HttpPost]
public ActionResult Delete(int id,Requirement Req)
{
var Requirement = purcls.Requirement.Where(o => o.Id == id).First();
if (Requirement != null)
{
purcls.Requirement.Remove(Requirement);
purcls.SaveChanges();
}
return RedirectToAction("Index");
}
}
}
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:
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.
Now you will see that this Purchaser's Entry is shown in the output window.
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.