Learning MVC-Part 3 : Creating MVC Application & Perform CRUD Operations Using EntityFramework

                                      In our first and second attempt to learn MVC, we learnt, what is MVC?, what is separation of concerns?, how to create a simple MVC application and perform CRUD operations on the application using LINQ to SQL.
My this article focuses on how to perform CRUD operations in MVC application by the use of an ORM(Entity Framework).
The article is an attempt to overcome the confusion related to how to use EntityFramework with MVC application in a very simple way.
Our Roadmap:

Our roadmap remains same,


There are few pre-requisites before we start with the article,
  •        We have running sample application that we created in second part of the article series.
  •        We have EntityFramework 4.1 package or dll on our local file system.
  •        We understand how MVC application is created.

What is ORM and EntityFramework?
The topic isn’t that scary as it seems to be. ORM(Object Relational Mapping) is basically an approach for storing data from domain/entity objects to relational database in an automated way without writing much code. A true ORM is independent of what database server we refer to, the code underlying ORM’s is database independent and can run with any database server having similar database with a structure needed by the application.ORM  has 3 main parts: Entity class objects, Relational db objects and information on how domain objects maps to relational db objects i.e. tables, views & storedprocedures. ORM helps us to keep our database design separate from our domain class design. This makes our application maintainable and extendable. It also automates standard CRUD operation (Create, Read, Update & Delete) so developer doesn’t require to code them manually J.
Now let’s have a look on standard definition of Entity Framework given by Microsoft:

“The Microsoft ADO.NET Entity Framework is an Object/Relational Mapping (ORM) framework that enables developers to work with relational data as domain-specific objects, eliminating the need for most of the data access plumbing code that developers usually need to write. Using the Entity Framework, developers issue queries using LINQ, then retrieve and manipulate data as strongly typed objects. The Entity Framework’s ORM implementation provides services like change tracking, identity resolution, lazy loading, and query translation so that developers can focus on their application-specific business logic rather than the data access fundamentals.

In a simple language, Entity framework is an Object/Relational Mapping (ORM) framework. It is an enhancement to ADO.NET, an upper layer to ADO.Net that gives developers an automated mechanism for accessing & storing the data in the database.
Hope this gives a glimpse of an ORM and EntityFramework.
EntityFramework Architecture:
Let’s have a glance over the architecture of EntityFramework,


Our Web Application interacts with Entity Data Model (Entity Framework), that acts as an interface between ADO.Net Provider and database, fetches/saves data in the same flow as described in the figure.
Perform CRUD operations using EntityFramework on MVC application:
Open the existing Learning MVC application that we created using LINQ to SQL,

I have made few changes in the existing application, just to make it easy to understand when we implement EntityFramework in it.
1.Changed the model class name from User to UserList,
3.        namespace LearningMVC.Models
4.        {
5.            #region User Model...
6.            /// 
7.            /// User Model Class, purposely used for populating views and carry data from database.
8.            /// 
9.            public class UserList
10.           {
11.               #region Automated Properties
12.               public int UserId { get; set; }
13.               public string FirstName { get; set; }
14.               public string LastName { get; set; }
15.               public string EMail { get; set; }
16.               public string Address { get; set; }
17.               public string PhoneNo { get; set; }
18.               public string Company { get; set; }
19.               public string Designation { get; set; } 
20.               #endregion
21.           } 
22.           #endregion
23.       }
     2. Changed the Solution name from LearningMVC to LearningMVCWithEF.
Steps to Follow:
1. Open the application, modify it by above given changes.
2. Delete the MyDBML.dbml class from the solution.
3. Do not build the solution now, it will result in an error, as we have removed the dbml file, so controller method accessing the dbml file will throw compile time errors.
4. Goto project right click and add new item, select Data in installed templates and add ADO.Nety EntityDataModel to the application,
Name it EFDataModel.edmx.
5.New window will be opened to choose model contents,
Since we are following Database First approach, select generate From Database.

6.Choose the connection and give the name to connection string as MVCEntities as shown in the figure, click next.

7.Provide connection details to the existing database, that we used for our existing application, database name was MVC.
If you don’t have existing one, create a new one with the attached db script files.
8. Choose data base objects, we have only one table , so choose that one as shown in figure,
Give model namespace as MVCModel.
9.We get in our solution one guest,Entity Data Model that we saw in Entity Framework Architecture above,

10. In web.config you can see a new connection string is added.Now you can comment/delete old connection string of LINQ to SQL,
11. Generating Strongly Typed Entity Model Classes:(taken from a blog)
We’ll be working with the strongly typed entity classes now. The Entity Data Model designer uses a code generator in Visual Studio called the Text Template Transformation Toolkit (T4). Entity Framework will automatically generate a User class. The code generator nowwill create a class based on our Entity Data Model.
By default, the designer uses a template that results in entity classes that inherit from Entity Framework’s EntityObject and a container class which inherits from EF’s ObjectContext.
These base classes can be cumbersome to work with for a number of reasons. While the ObjectContext is extremely useful when you need a lot of control over Entity Framework’s behavior, the lighter weight DbContext provides access to the most commonly needed tasks and simplifies your coding.
Microsoft provides a number of alternative T4 templates for generating classes from the EDM.  When you installed the EF 4.1, a template for creating simpler classes including the DbContext was added to Visual Studio. Let’s tell the designer to use this template instead of the default.
·      Right click on the model’s designer surface.
·      From the context menu, choose Add Code Generation Item.
·      In the Add New Item dialog that opens, select Code from the list of installed templates types on the left.

·      Choose the ADO.NET DbContext Generator then click the Add button.

Two new files will be listed in Solution Explorer, Model1.Context.tt and Model1.tt. These are template files. Expand the templates to see the generated classes as shown in following figure,
12. When we open these two new guests, we see the context class to access model and model class for our user entity is already created, with full code,

Have you noticed that we have’nt written a single line of code by our hand, this is the revolution that EntityFramework has come up with, Let’s give a round of applause to our smart work,

Time to write some code now:
Till now we have not written a single line of code, but to access th context class, we need to change the logic from accessing LINQ to SQL data context to EntityFramework data context in the controller we created earlier in second part of the tutorial.
Steps to follow:
Step1: Bind all our views with UserList class, later it was user class, but we changed that to UserList class (remember????)
Step2:Open the controllers, change the access mechanism of context class as shown below for e.g. Index Action,
public ActionResult Index()
var dbContext = new MyDBDataContext();
var userList = from user in dbContext.Users select user;
var users = new List();
if (userList.Any())
foreach (var user in userList)
users.Add(new LearningMVC.Models.User()
{ UserId = user.UserId, Address = user.Address,
Company = user.Company, FirstName = user.FirstName,
LastName = user.LastName, Designation = user.Designation,
EMail = user.EMail, PhoneNo = user.PhoneNo });
ViewBag.FirstName = "My First Name";
ViewData["FirstName"] = "My First Name";
var tempData = TempData["TempData Name"];
return View(users);
public ActionResult Index()
var dbContext = new MVCEntities() ;
var userList = from user in dbContext.Users select user;
var users = new List();
if (userList.Any())
foreach (var user in userList)
users.Add(new LearningMVC.Models.UserList()
{ UserId = user.UserId, Address = user.Address,
Company = user.Company, FirstName = user.FirstName,
LastName = user.LastName, Designation = user.Designation,
EMail = user.EMail, PhoneNo = user.PhoneNo });
ViewBag.FirstName = "My First Name";
ViewData["FirstName"] = "My First Name";
var tempData = TempData["TempData Name"];
return View(users);
You can see we just had to change access mechanism, mere change of 2-3 lines, and not anything in the logic of application.
Step3: Like wise do the same for all the Actions. I am not showing how to do here, but you can compare the source codes and now can do by yourself.
Step4: Note LINQ to SQL context class uses InsertOnSubmit()/DeleteOnSubmit() and SubmitChanges() method for Insert, update,Delete but EF context class uses .Add(), .SaveChanges().So do it skillfully when required.
Step5: All set now, rebuild your application, and you’ll not get a single error.Now ready to run.
Step6: When you run the application, it runs as was running previously and now you can perform CRUP operations as an end user to the application, and test the application .

Nothing more dude, we are done with Entity framework’s database first approach now.You can applause again, and take some rest.
We have already moved to one step on advanced level of CRUD operations in MVC.There is more to learn in MVC and Entity Framework, that we’ll be covering in upcoming articles.In this article we mastered how to perform CRUD operations in MVC application using EntityFramework’s database first approach,next article will focus on my favourite CodeFirst approach J.
Happy Coding.

Learning MVC-Part 2 :Creating MVC Application & Perform CRUD operations using LINQ to SQL

                           In first part of the tutorial series we got a glimpse of MVC. In this part we’ll focus on practical implementation of MVC Pattern. I don’t need to  explain about theory of MVC as we have already covered this in previous part of the article.
Our Roadmap:
                      We stick our agenda as follows,
Topics to be covered:
1.     Creating MVC project from scratch.
2.     Adding Controllers, Views and Models.
3.     Creating sample database and use LINQ to SQL for communication.
4.     Perform CRUD operations in MVC application using LINQ to SQL.
5.     Understand ViewData, ViewBag and TempData.
6.     Model Validation by System.Component.DataAnnotation.
1.    Creating MVC project:
     Step1: Open Visual Studio 2010/2013,I am using 2010.Goto File=>New=>Project and select  ASP.Net MVC3 Web Application, as shown below,
Name the application as LearningMVC.
Step2: A project template selection window will be opened, select Empty in that.Select View Engine as Razor and press OK.
Step3: Now our solution is ready with an empty MVC application,
We can clearly see that the solution contains some extra folders in comparison to traditional Asp.Net web application.
We got Models, Views and Controllers folder and a Shared folder in Views folder. The folders as name denotes are used to hold the respective MVC players model-view-controllers, the shared folder in Views contains the _Layout.cshtml, that can be used as the master page for the views which we create.
We see the global.asax file that contains a default routing table, that defines the route to be followed when request comes, it says that when request comes to Home controller, the Index action of that Home Controller has to be called,
Actions are the methods defined in Controllers, that can be called defining a route, the Action methods can also contain parameters, in above mentioned figure, it says that Home controller has an Action Index which contains an optional parameter id.
When we run our application, we get something as shown below,
It says that the resource which we are looking for can not be found.The request by default follows the default route as mentioned in global.asax, i.e. go to controller Home and invoke method Index.Since we don’t have any of these yet, the browser shows this error.
Never mind, lets make the browser happy.
2.  Adding Controllers ,View and Models:
Step1: Create a My Controller by right clicking on Controllers folder and add a controller named My, add the controller with empty read/write actions, it will give us a class with few default generated actions.
Note that there are two Actions for every Action name, one is for Get i.e. when view loads for first time, and second one is for POST, when View is submitted with some data.
Change global.asax RegisterRoutes method as,
  public static void RegisterRoutes(RouteCollectionroutes)
                “Default”, // Route name
                “{controller}/{action}/{id}”, // URL with parameters
                new { controller = “My”, action = “Index”, id = UrlParameter.Optional } // Parameter defaults
Note: we have changed the name of controller as per our added controller.
Step2: We can see that we have Actions but they return a View, so we need to create Views for them.But before this we’ll create a Model named User for our Views.Right click on Model folder add a class named User,
Add following properties to User class,
Now our model is created and we can create Views bound to this particular model.
Step3: Go to controller, right click on empty Actions of the controller and from the context menu select AddView on the top.By default the View name is same as of Actions name.
e.g. For Details,
Select Viewname as Details,Model class as User, and Scaffold Template as Details.This template specifies the role of the View, that this view will show the details of the User(entity).Click add.
Likewise perform this operation for all the Actions, and create Views.
Note that Views are automatically added, to Views folder under My folder(auto created as per Controller’s name).This is to maintain a particular structure for MVC, so that we don’t have to take overhead to maintain it.




   Now we have controller as well as Views, so if we run the application we get,

i.e. Index Action of our My controller is Fired that returned Index View. 
3. Creating sample database and use LINQ to SQL for communication.
                        Our MVC application is ready but, rather than displaying dummy data, I would go for running the application talking to a data base so that we can cover wider aspect of the application.
Step1: Create a database, script is given in the attachment, just execute it over Sql Server 2005/2008.
Step2: Add new Item to the solution, and select LINQ to SQL class, call it MyDB.dbml
Our Solution looks like,
Step3:Open Server explorer of Visual Studio, Open a connection, by providing Server name and existing database name in Server Explorer Open Connection window,


Click OK.Our solution looks like,
Step4: Drag the User table to dbml designer window,we get the table in class diagram format in designer window,
When we open MyDB.designer.cs, we get MyDBDataContext class.This class holds databse User table information in the form of Class and Properties.For every column of the table, properties are created in the class, and we can use these properties to get/set values from/in database.
4. Perform CRUD operations in MVC application using LINQ to SQL.

We now have a database, a context class to talk to data base and a MVC application to perform CRUD operations in database using the context class.
Step1 Read :
i) Go to Index Action, make an instance of context class, We can get all the table and column names in that context’s instance.
ii) Make a query to display all the records on Index view.
iii) Populate the User Model that we created earlier, and pass it to the Index view(Index View will be of List type Item template)
When we run the application, we get empty list, i.e. we don’t have records in database,
Step2 Create:
i)First write code for creating a user, for the first time for Get Action of create, always an empty view will be returned.
ii)When we post some data on click of submit of Create, then we need to make a data entry in table for creating a new user.
iii)When form posted, it fires Post Action of Create with the already bound User model properties to view fields, we’ll retrieve these model properties and make an instance of context class populate context User and submit to data base.
 iv)Redirect action to Index, and now a record will be shown on the Index View.We successfully created a user J.

v) In database :

Step3 Update & Step4 Delete:
Now we are smart enough to perform update and delete by ourself, this I leave for reader’s understanding capabilities, below are the screens for Update and  Delete.
Edit Code:
Get Action View of Edit:
Edited few fields:
Update reflected in database:
Code to show details of a particular user :
Details Screen:
Note : Details Action do not have POST one, as nothing to post to controller.
Likewise for Delete:
Back to List after Delete:
In database after delete:
Yes, all the CRUD operations done.Now we know MVC.
There are few basic scenarios that I want to discuss before finishing with the First Part, like passing data from Controller to Views, between Controllers etc and about Model validation.
5. Understand ViewData, ViewBag and TempData.
I wanted to take this topic as there is much confusion  regarding these three players.
MVC provides us ViewData, VieBag and TempData for passing data from controller, view and in next requests as well. ViewData and ViewBag are similar to some extent but TempData performs additional roles. Lets get key points on these three players:
ViewBag & ViewData :
I have written sample test code in the same application which we are following from the beginning,
         Populate ViewData and ViewBag on Index action of My Controller,
         Code in View to fetch ViewData/ViewBag,
         When run the application, we get on screen,
Following are roles and similarities between ViewData and ViewBag:
Ø  Maintains data when move from controller to view.
Ø  Passes data from controller to respective view.
Ø  Their value becomes null when any redirection occurs , because their role is to provide a way to communicate between controllers and views. It’s a communication mechanism within the server call.
Differences between ViewData and ViewBag (taken from a blog):
Ø ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys.
Ø ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
Ø ViewData requires typecasting for complex data type and check for null values to avoid error.
Ø ViewBag doesn’t require typecasting for complex data type.
TempData is a dictionary derived from TempDataDictionary class and stored in short lives session.It is a string key and object value.
It keep the information for the time of an HTTP Request. This mean only from one page to another. Helps to maintain data when we move from one controller to other controller or from one action to other action. In other words when we redirect, “Tempdata” helps to maintain data between those redirects. It internally uses session variables. Temp data use during the current and subsequent request only means it is use when we are sure that next request will be redirecting to next view. It requires typecasting for complex data type and check for null values to avoid error. Generally it is used to store only one time messages like error messages, validation messages.
I added a TempData in Edit Action as,
        public ActionResultEdit(int? id, UseruserDetails)
            TempData[“TempData Name”] = “Akhil”;
And when View redirected to Index Action,
i.e. I get the TempData value across Actions.
6.Model Validation:
 We can have many methods for implementing validation in our Web Application Client Side, Server Side etc…
 But MVC provides us a feature with which we can annotate our Model for validation by writing just one/two line of code.
 Go to the Model class User.cs, add [Required(ErrorMessage = “FirstName is required”)] on the top of FirstName property as,
public int UserId { get; set; }
        [Required(ErrorMessage = “FirstName is required”)]
        public stringFirstName { get; set; }
        public stringLastName { get; set; }
Now when we run the application, and try to Edit/Create user without specifying FirstName, we get,
Surprised!, Yes model validates itself with these annotations, there are many more validators like required field one that I used.
Do not forget to include usingSystem.ComponentModel.DataAnnotations; Namespace, when using Model Validation.This is the namespace that holds classes used for validation.
                 Now we know what MVC is ,how to Implement it,its advantages,CRUD operations in MVC.Upcoming parts of the tutorial will be focussing on more advanced topics like EntityFramework, Repository Pattern,Unit Of Work Pattern.Code First Approach.


Happy Coding J.

Read more:

Other Series

My other series of articles:

For more informative articles visit my Blog.

For more technical articles you can reach out to CodeTeddy.

Learning MVC-Part 1 : Introduction to MVC Architecture and Separation of Concerns

After having gone through numerous of blogs and articles, I came to a conclusion that very few of the genuine writers have explained the topic from basics to its details in a full-fledged way with a working application. My effort in this MVC articles series would be to cover almost all the aspects of MVC starting from creating simple app and connecting with the database with various Microsoft providers. We’ll be gradually moving forward part by part to understand and practically implement all the scenarios.
Road Map:
All set, now we can start our journey with Part1.
Part1: Introduction to MVC architecture and Separation of Concerns.
Topics to be covered:
  • 1.     What does MVC mean.
  • 2.     Understand MVC Architecture.
  • 3.     Separation of Concerns


Model: The business entity on which the overall application operates. Many applications use a persistent storage mechanism (such as a database) to store data. MVC does not specifically mention the data access layer because it is understood to be encapsulated by the Model.
View: The user interface that renders the model into a form of interaction.
Controller: Handles a request from a view and updates the model that results a change in Model’s state.
To implement MVC in .NET we need mainly three classes (View, Controller and the Model).
MVC Architecture:
           The choice of MVC comes when we go for a solution where separation of concerns, ease of maintainability and extensibility of an application matters a lot. As per the architecture given below, we can see the request-response flow of a MVC application.

The architecture is self explanatory in itself. Browser as usual sends a request to IIS,IIS searches for the route defined in MVC application and passes request to the controller as per route, the controller communicates with model and passes the populated model(entity) to View(front end), Views are populated with model properties, and are rendered on the browser, passing the response to browser through IIS via controllers which invoked the particular View.

Separation of Concern:
As per Wikipedia ‘the process of breaking a computer program into distinct features that overlap in functionality as little as possible’. MVC design pattern aims to separate content from presentation and data-processing from content. Theoretically well, but where do we see this in MVC? One is reasonably clear – between the data-processing (Model) and the rest of the application.
When we talk about Views and Controllers, their ownership itself explains separation.The views are just the presentation form of an application, it does not have to know specifically about the requests coming from controller. The Model is independent of View and Controllers, it only holds business entities that can be passed to any View by controller as per need of exposing them to end user.The controller in independent of Views and Models, its sole purpose is to handle requests and pass it on as per the routes defined and as per need of rendering views.Thus our business entities(model), business logic(controllers) and presentation logic(views) lie in logical/physical layers independent of each other.
Now we know why and where to use MVC, in another part of learning MVC we’ll be creating a MVC application from scratch, exploring the practical implementation of MVC.

Read more:

Other Series

My other series of articles:

For more informative articles visit my Blog.

For more technical articles you can reach out to CodeTeddy.


Javascript Alert in C#



/// A JavaScript alert 


public static class Alert



    /// Shows a client-side JavaScript alert in the browser.

    /// The message to appear in the alert.

    public static void Show(string message)


        // Cleans the message to allow single quotation marks

        string cleanMessage = message.Replace(“‘”“\\'”);
        string script = string.Format(“$(document).ready(function(){alert(‘{0}’);});”, cleanMessage);

// Gets the executing web page

        Page page = HttpContext.Current.CurrentHandler as Page;

// Checks if the handler is a Page and that the script isn’t all ready on the Page

        if (page != null && !page.ClientScript.IsClientScriptBlockRegistered(“alert”))


            page.ClientScript.RegisterClientScriptBlock(typeof(Alert), “alert”, script);




Session Helper Class (Facade)

 using System.Web;

/// Static Session facade class

public static class SessionHelper
# region Private Constants
private const string userId = “UserId”;
private const string projectId = “ProjectId”;
# endregion
#region Private Static Member Variables
private static HttpContext thisContext;
#region Public Static Methods

/// Clears Session

public static void ClearSession()

/// Abandons Session

public static void Abandon()
#region Public Static Properties

/// Gets/Sets Session for UserId

public static string UserId
if (HttpContext.Current.Session[userId] == null)
return “”;
return HttpContext.Current.Session[userId].ToString();
set { HttpContext.Current.Session[userId] = value; }
public static string ProjectId
if (HttpContext.Current.Session[projectId] == null)
return “”;
return HttpContext.Current.Session[projectId].ToString();
set { HttpContext.Current.Session[projectId] = value; }
//Use as: SessionHelper.UserId=”user1″;
//        string user=SessionHelper.UserId;
//        SessionHelper.Abandon();

Use the ENUM object to manipulate Enumerated Values

Enums are a tremendously easy way to make your code understandable. In the bad old days, when working on someone else’s program I’d be forced to decode code like this:
Dim cust As New Customer
cust.Type = 0
With an Enum, everything is more obvious:
Dim cust As New Customer
cust.Type = CustomerTypes.Deadbeat
What takes Enums to the next level are the static methods built into the Enum class. For instance, if I want to turn an Enum into an array of strings, I can use the Enum class’s GetNames method:
Dim cTypes As String() = [Enum].GetNames(GetType(CustomerTypes))
Because of the way Visual Basic handles names, Enum has to be enclosed in brackets to prevent syntax errors. C# doesn’t require those brackets:
string[] cTypes = Enum.GetNames(typeof(CustomerTypes));
I can then bind the output from GetNames to any listing control to get a list of the names in the Enum displayed in my user interface:
MyListBox.ItemsSource = Enum.GetNames(typeof(CustomerTypes));
GetNames shows the basic structure of the Enum class’s static methods: the first parameter to any method is always the Type of the Enum you want to work with. For instance, if you have code in a Web Service that’s passed the value of an Enum, you can convert that value into the name of the corresponding Enum entry using the Enum class’s GetName method. As before, the first parameter is the type of the Enum; the second parameter is the value you’re looking up:
Dim inputValue As Integer = 1
Me.MyTextBox.Text = [Enum].GetName(GetType(CustomerTypes), inputValue)
Parse goes one better and converts a string containing one of the names in an Enum into the Enum item itself. This code, for instance, sets the Customer object’s Type property to the appropriate Enum item based on a string value:
Dim custTypeString As String = "DeadBeat"
cust.Type = [Enum].Parse(
GetType(CustomerTypes), custTypeString);
Visual Basic doesn’t require the explicit cast to use Parse:
string custTypeString = "DeadBeat";
cust.Type = (CustomerTypes) Enum.Parse(
typeof(CustomerTypes), custTypeString);
If the string value you’re passing to Parse isn’t an item in the Enum, the Parse method throws an exception. To avoid that, you can use the Enum’s TryParse method which, while it still won’t do the conversion, won’t throw an exception either. An even better answer is to use the Enum’s IsDefined method to see if the item exists before trying to retrieve it:
if (Enum.IsDefined(typeof(CustomersType), custTypeString))
Customers ctype = (CustomersType) Enum.Parse(
typeof(CustomersType), custTypeString);
ErrorLabel.Text = "Not a valid customer type.";
(Taken from a blog.)