May 14, 2011

ASP.Net MVC Sample Application using ADO.Net Entity Framework

How we can use ASP.NET MVC Framework check this post

In the above Post example I have used ADO.NET to insert the data in SQLServer Db (Student Table)
Now In this post I 'll add one more view Where To Select the records from the above table I 'll
use ADO.NET Entity framework.

1.)Creating the ADO.NET Entity Data Model
In order to use the Entity Framework, you need to create an Entity Data Model. You can take advantage of the Visual Studio Entity Data Model Wizard to generate an Entity Data Model from a database automatically.
Follow these steps:

1)Right-click the Models folder in the Solution Explorer window and select the menu option Add, New Item.
2)In the Add New Item dialog, select the Data category
3)Select the ADO.NET Entity Data Model template, give the Entity Data Model the name Model1.edmx,
4)Click the Add button. Clicking the Add button launches the Data Model Wizard.
5)In the Choose Model Contents step, choose the Generate from a database option and click theNext button

6)In the Choose Your Data Connection step, select the MoviesDB.mdf database connection, enter the entities connection settings name TestMVEntities3, and click the Next button

8)In the Choose Your Database Objects step, select the TestMVC database table and click the Finishbutton

After you complete these steps, the ADO.NET Entity Data Model Designer (Entity Designer) opens.
Model1.designer.cs will be automatically generated and It will Map the Database and the tables as the
entity classes and To Communicate with the DB now we can Communicate with The entity classes objects
We can use EntitySQl query syntax or LINQ to Sql Below is the code sample for both.

To Select Records from student table using entity sql I added below highlighted code in StudentController.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TestMVCapplication.Models;
using System.Data;
using System.Data.SqlClient;
using System.Data .Objects ;

namespace TestMVCapplication.Controllers
    public class StudentController : Controller
        SqlConnection connObj = new SqlConnection();
        DataSet ds;
        SqlCommand objCommand;
        SqlDataAdapter objAdapter;

        // GET: /Student/
        public ActionResult GetStudent()
            return View();

        public ActionResult Viewstudent()

            TestMVCEntities3 DBobj = new TestMVCEntities3();
                    //ENTITY SQL QUERY SYNTAX
                    ObjectQuery query = DBobj.CreateQuery<Student>("Select value s from student as s");
                    var res = query.Execute(MergeOption.NoTracking) as IEnumerable<Student>;
                    int i=0;
                    foreach (Student  c in res)
                      // Response .Write (c.Name);
                       ViewData["name"+i.ToString()] = c.Name;
                       ViewData["email" + i.ToString()] = c.Email;
                       ViewData["comment" + i.ToString()] = c.Comment;

                     //LINQ TO ENTITY QUERY
                     //var query1 = from Student  c in DBobj.Student
                     //               select c;

                     //foreach (Student  c in query1)
                     //       {
                     //          Response .Write (c.Name);
                     //       }

            return View();


        public ActionResult GetStudent(StudentModel model)
            Response.Write(model.Name + model.Comment + model.Email);
            //code to insert data in DB using ADO.NET
            connObj.ConnectionString = "Data Source=.\\sqlexpress;Initial Catalog=TestMVC;Integrated Security=True";
        SqlCommand comm = new SqlCommand("insert into student(name,email,comment) values(@name,@email,@comment)", connObj);
            comm.Parameters.Add("@name", SqlDbType.VarChar , 50).Value =model .Name ;
            comm.Parameters.Add("@email", SqlDbType.VarChar, 50).Value = model.Comment;
            comm.Parameters.Add("@comment", SqlDbType.VarChar, 50).Value = model.Email;

        int result = comm.ExecuteNonQuery();
        if (result != 0)
            Response.Write(" added");

            return View();



From the above Viewstudent I selected records from the Student Table and 
Inserted those iv ViewData to able to access them in the Viewstudent View
I added one View named Viewstudent.aspx in in views/Student


<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

   <% for (int i = 0; i <= ViewData.Count;i++ )
      { %>

     Name: <%= ViewData ["name"+i.ToString ()]%>
    <br />
     Email:<%= ViewData ["email"+i.ToString ()]%>
    <br />
     Comment:<%= ViewData ["comment"+i.ToString ()]%>
    <br />
        <hr />
<% } %>


To Link this View in Previous MVC Example's view I added the below highlighted line of code there 


<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<TestMVCapplication.Models.StudentModel>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <form id="form1" runat="server">


 <% Html.EnableClientValidation(); %> 
    <% using (Html .BeginForm() ){%>
        <%= Html.ValidationSummary(true, "A few fields are still empty") %>
       <%= Html.ActionLink("ViewstudentData", "Viewstudent", "Student")%>
             <legend>Student Detail</legend>
            <div class="editor-label">
                <%= Html.LabelFor(m => m.Name) %>
            <div class="editor-field">
                <%= Html.TextBoxFor(m => m.Name) %>
                <%= Html.ValidationMessageFor(m => m.Name) %>
            <div class="editor-label">
                <%= Html.LabelFor(m => m.Email) %>
            <div class="editor-field">
                <%= Html.TextBoxFor(m => m.Email) %>
                <%=Html.ValidationMessageFor(m => m.Email) %>
            <div class="editor-label">
                <%= Html.LabelFor(m => m.Comment) %>
            <div class="editor-field">
                <%= Html.TextAreaFor(m => m.Comment, 10, 25, null) %>
                <%= Html.ValidationMessageFor(m => m.Comment) %>
                <input type="submit" value="Submit" />
        <p id="result"><%=TempData["Message"] %></p>
    <% } %>

Now Run the application again and Click On Student Menu Link

Click On ViewStudentData Link
and you ll get the selected records in the view 


  1. If you want to increase уouг knοwledge јust
    kееp visіtіng thiѕ web page аnd be updated wіth the most
    up-tο-date news updаte ρosted here.
    My web site :: instant payday loans