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:

Invalid Object Name with Entity framework -EFCodeFirstCTP5

Recently I was working on one sample application with EFCodeFirst with the existing database.After doing all the coding I have found a error “Invalid object name 'dbo.Customers'.”. Following was my code for data context.

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

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

      protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
      {
     
      }
  }
}

And following is code for my entity model class.

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; }
}

Once I run the application I was getting following error.

Error

As you can see from my code that it should be dbo.customer name. So after digging into the issue I have found that I need to remove the plural table name. Here is a forum that is saying the same.

http://social.msdn.microsoft.com/Forums/en-ie/adonetefx/thread/719f3e4d-073b-49fe-9968-945acde27bb7.

Now there are two ways of resolving this issue.
1) Either explicitly map entity class with table attribute like I have changed my code like following.

[Table("Customer",SchemaName="dbo")]
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; }
}

Another one is you need to remove default plural table name via overriding the onModelCreating event like following.

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>();
      }
  }
}

That’s it now error is gone. My code is work perfectly!!. Hope this will help you.Stay tuned for more..Till that happy programming.

Shout it

kick it on DotNetKicks.com
Share:
Saturday, July 2, 2011

Wohooooo!!! I got Microsoft MVP award again for Visual C#

Yesterday I got great news from Microsoft. I have been awarded as Microsoft MVP again for year 2011-2012. Yesterday I got following email.



Dear Jalpesh Vadgama,

Congratulations! We are pleased to present you with the 2011 Microsoft® MVP Award! This award is given to exceptional technical community leaders who actively share their high quality, real world expertise with others. We appreciate your outstanding contributions in Visual C# technical communities during the past year.

It is really one of the proudest moment of my professional life. When you get this kind of appreciation its feel great.

On this occasion I would like to thank my Friends,Employer,co-workers, Community friends and readers for providing support for me. I would also like to thank my MVP lead Abhishek Kant for guiding me throughout year. Last but not least my family members who are been there for me for my every ups and down. My father and mother who is inspiration of mine. My lovely brother Vishal who encourage me to do all this and My Lovely wife Reena who is supporting me for this in every possible way and my little champ Teerth from whom I am getting energy to do this.

Once again Thanks Microsoft for this.

Shout it
Share:

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