Tuesday, July 5, 2011

CRUD Operation with ASP.NET MVC and EFCodeFirst Part-1

I have been playing with EFCodeFirst now and I found it very interesting with that you could write your application fast and easily. So I have decided to write series of blog posts for CRUD Operations using ASP.NET MVC 3 and EFCodeFirstCTP5.0 . You can very easily create CRUD within some minutes of code. So let’s start first thing is to create an ASP.NET MVC 3 application like following.

ASP.NETMVCApplication

Once you click OK. It will ask for the which type of View your are going to use. I have used Razor and HTML5 Semantic like following.

RazorView

Now once we have create a application Now its time to add EFCodeFirst reference via NuGet. So Go to the Library Package Manager –> Manage Nuget Package Manager. It will open up a dialog like following. Search EFCodeFirst and then it will fine EFCodeFirst package like following.

EFCodeFirst

Once you click Install it will add reference to your ASP.NET MVC Application like following.

EntityFrameworkRerence

So now all the things are set Its time to code now. So first I have Create my Table which is very simple table called Customer like I have used in previous post. For your reference I am putting the create table script below.

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Customer](
   [CustomerId] [int] IDENTITY(1,1) NOT NULL,
   [FirstName] [nvarchar](50) NULL,
   [LastName] [nvarchar](50) NULL,
   [Address] [nvarchar](256) NULL,
   [City] [nvarchar](50) NULL,
CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED
(
   [CustomerId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY

Now let's create our entity class called customer like following.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace CodeSimplified.Models
{
   public class Customer
   {
       public int CustomerId { get; set; }
       public string FirstName { get; set; }
       public string LastName { get; set; }
       public string Address { get; set; }
       public string City { get; set; }
   }
}

Now Its time to create a our datacontext class So I have created MyDataContext class inherited from the DBContextClass . In that I have defined my customer dbset and Also I override the default plural behaviour in ModelCreating Table. DBSet will tell datacontext which table we need to refer. So following is code for that.

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Data.Entity.ModelConfiguration.Conventions.Edm.Db;

namespace CodeSimplified.Models
{
   public class MyDataContext:DbContext
   {
       public DbSet<Customer> Customer { get; set; }

       protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
       {
           modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
       }
   }
}

Now our database access stuff is ready now It’s time to create controller. So I have clicked controller folder and click on add new controller so add controller dialog box will appear like following.

AddController

It will create a controller class like following.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CodeSimplified.Controllers
{
   public class CustomerController : Controller
   {
       //
       // GET: /Customer/

       public ActionResult Index()
       {
           return View();
       }

       //
       // GET: /Customer/Details/5

       public ActionResult Details(int id)
       {
           return View();
       }

       //
       // GET: /Customer/Create

       public ActionResult Create()
       {
           return View();
       }

       //
       // POST: /Customer/Create

       [HttpPost]
       public ActionResult Create(FormCollection collection)
       {
           try
           {
               // TODO: Add insert logic here

               return RedirectToAction("Index");
           }
           catch
           {
               return View();
           }
       }
      
       //
       // GET: /Customer/Edit/5

       public ActionResult Edit(int id)
       {
           return View();
       }

       //
       // POST: /Customer/Edit/5

       [HttpPost]
       public ActionResult Edit(int id, FormCollection collection)
       {
           try
           {
               // TODO: Add update logic here

               return RedirectToAction("Index");
           }
           catch
           {
               return View();
           }
       }

       //
       // GET: /Customer/Delete/5

       public ActionResult Delete(int id)
       {
           return View();
       }

       //
       // POST: /Customer/Delete/5

       [HttpPost]
       public ActionResult Delete(int id, FormCollection collection)
       {
           try
           {
               // TODO: Add delete logic here

               return RedirectToAction("Index");
           }
           catch
           {
               return View();
           }
       }
   }
}

Now once our controller is ready now its time to write some code for Index Action Result which we are going to have a list of customer. So I have changed Index Action Result like following to return customer view.

public ActionResult Index()
{
   using (var databaseContext=new Models.MyDataContext())
   {
       return View(databaseContext.Customer.ToList());
   }
}

Now let create a view from the controller. So Selected a view in right click Add View from Index Action Result. Here I have selected strongly typed view with Customer Model and selected list Template like following.

AddView

That’s it we are done with listing of the customer. Now its time to run our application and following is the output as expected.

Output

Hoped you like this…Stay tuned for more.. Till that happy programming.

Shout it

kick it on DotNetKicks.com
Share:

0 comments:

Post a Comment

Your feedback is very important to me. Please provide your feedback via putting comments.

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews