Monday, June 23, 2014

Simple example for Asp.net MVC 4 and Entity Framework for Add/Edit/Delete/View/List Customers

Today we will create very simple Asp.net MVC 4 application with entity framework which will give you basic idea about MVC and entity framework. I am going to use “database first” workflow for entity framework.

Let’s start with following steps:

Step 1: Create a new project with .net 4.5 and choose Asp.net MVC 4 Web application and give name “MvcDemo” and click ok.

Step 2: Now choose “Empty” in template selection. View engine will be “Razor” by default and click Ok. This will create project with basic files and folders.

Step 3: Please create database and create “customer” table with following script.

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

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

GO

Step 4: We will create entity model in our project, for this, right click on “Models” folder and add new item as following and give name “MvcModel”.



Step 5: Select “Generate from database” and click next :



Step 6: Choose “connection string”, click “new connection” and give your database connection and name it “MvcDataEntities” and click Next.



Step 7: Choose “Customer” table and click on finish.



Step 8: This will create model :



Step 9: We have model, now we will create controller which will automatically create views for us.

Step 10: Right click on “Controllers” folder and add “HomeController” with Template “MVC controller with read/write actions and views, using Entity Framework." and click Add.



Step 11: This will create “HomeController” and also associated Views like create.cshtml, delete.cshtml, edit.cshtml etc… :



Step 12: Make it start up project and run. Initial screen will look like following:



Step 13: Click on “Create New” and it will give you following error:



Step 14: To solve this, you have to run nuget package with following command :
Install-Package Microsoft.AspNet.Web.Optimization


Step 15: once you run this nuget package, you have to add namespace in web.config like following.
<add namespace="System.Web.Optimization"/> 

Step 16: Now run your project and you can successfully add, edit, delete and view list of cutomers.

No comments:

Post a Comment

React-select is very slow on larger list - Found solution - using react-window

 I had more than 4000 items in searchable dropdownlist. I have used react-select but it was very slow. finally I found complete solution to ...