Wednesday, 20 May 2015

Data Access from databse using Entity framework


Here we will learn How to access value from database using entity framework in Asp.net MVC.
1.   Go to your SQL server Management system and create a database and execute the following script.
Create Table Student
(
     StudentID int identity primary key,
     StudentName nvarchar(50),
     Gender nvarchar(50),
     SchoolName nvarchar(50)
)
GO



Insert into Student values ('Munesh','Male','VIT')
Insert into Student values ('Rahul','Male','ABC')
Insert into Student values ('Reet','Female','XYZ')
Insert into Student values ('Anshuman','Male','PQR')

2.   How a controller respond to a user request  :- It Gets the data from modal a modal and transfer this request to  the view then view render the data. Modal can be a entity or a business objects.
3.   Retrieving the data from database table using entity framework ,1st we have to install entity framework using nugget package manager for this go to Entity framework tutorial. Add a reference of entityFramework.
4.   Now add  a StudentContext.cs class to your modal folder
using System.Data.Entity;

public class StudentContext : DbContext
{
    
public DbSet<Student>  _students {get; set;}
}

The use of StudentContext class is for establishing the connection to our database
5.   Now add a connection string  in Web.Config file
<connectionStrings>
  
<add name="StudentContext" 
        
connectionString="server=.; database=MVCApplication; integrated security=SSPI"
        
providerName="System.Data.SqlClient"/>
</connectionStrings>


6.   Create a class As Student.cs in Modal folder and MAP it with database table, for mapping this employee modal class with database table we will use “Table” attribute. For this Attribute we need DataAnnotations namespace.


using System.ComponentModel.DataAnnotations.Schema;


namespace MvcApplication1.Models
{
   [Table("Student")]
    public class Student
    {
        public int StudentId { get; set; }
        public string StudentName { get; set; }
        public string Gender { get; set; }
        public string StudentSchool { get; set; }
    }
}


7.   Now we need to change in Controller class for getting the value from database. For this  I added a Controller class with name Home Controller by default it contain a Index method.
1.   First in index method we need to call the “StudentContex”t class for making the connection this StudentContext class it connected with Web config file.
2.   Here if we want data according to ID then we need to pass ID to this  function and then we will retrieve student detail according to that id.
using System.Web.Mvc;
using MvcApplication1.Models;

namespace MvcApplication1.Controllers
{
    public class StudentController : Controller
    {
       
        public ActionResult StudentDetail(int id)
        {
            StudentContext _context = new StudentContext();
           Student _student =  _context._studentDb.Single(c => c.StudentId         == id);

            return View(_student);
        }

    }
}


8.   Now we will add a view for this method so for that see the following code
@model MvcApplication1.Models.Student

@{
    ViewBag.Title = "StudentDetail";
}

<h2>StudentDetail</h2>

<table style="font-family:Arial">
    <tr>
        <td>
            Student ID:
        </td>
        <td>
            @Model.StudentId
        </td>
    </tr>
    <tr>
        <td>
            Name:
        </td>
        <td>
            @Model.StudentName
        </td>
    </tr>
    <tr>
        <td>
            Gender:
        </td>
        <td>
            @Model.Gender
        </td>
    </tr>
    <tr>
        <td>
            City:
        </td>
        <td>
            @Model.SchoolName
        </td>
    </tr>
</table>


9.   Here we need to remember that in  “Global.asax” file we will add a line of code
Database.SetInitializer<MvcApplication1.Models.StudentContext>(null);



Here “Database” is stored in “using System.Data.Entity” namespace. The use of this “SetInitializer” is that , It creates table if we don’t have table in database which is given in Employee modal class by us as an Table Attribute.

10.                Run Your application and give the path as “http://localhost/MvcApplication1/student/StudentDetail/1”  or you can set Controller name and Action method name in Route.Confing File you will get expected result from here means it show the data which is exists in database table on ID =1.






Note :-  While Running if you get error like “Login failed for user 'IIS APPPOOL\DefaultAppPool'” then you refer this link

Modal in Asp.Net MVC

Here we will learn Modal in Asp.net MVC, If we want to show the Student data from database “Student “ Table then we need to define properties of a student and need to display student information.

1.   Go to your application and right click on Modal folder and add a class to this folder then give the name of that class as Student.cs means this class contain of all the properties of a student, Now Define the  properties of Student.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcApplication1.Models
{
    public class Student
    {
        public int StudentId { get; set; }
        public string StudentName { get; set; }
        public string Gender { get; set; }
        public string StudentSchool { get; set; }
    }
}


2.   Now Add a controller to your application for that go to solution explorer and right click on Controller and a controller and give the name for this controller As Student.
When we click on add then in this Student controller class there is a bydefault method is index , so change this method name as “studentdetail”.
using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    public class StudentController : Controller
    {
       
        public ActionResult StudentDetail()
        {
            return View();
        }

    }
}


Here if i try to access Student.cs class , it will not be assessable because it is in “MvcApplication1.Models” namespace however this Controller class exists in “namespace MvcApplication1.Controllers” namespace. So for accessing the student.cs class add the namespace in controller class and define the value of student properties

using System.Web.Mvc;
using MvcApplication1.Models;

namespace MvcApplication1.Controllers
{
    public class StudentController : Controller
    {
       
        public ActionResult StudentDetail()
        {
            Student _student = new Student()
            {
                StudentId = 1,
                StudentName = "munesh",
                Gender = "Male",
                StudentSchool = "VIT"
            };

            return View();
        }

    }
}



3.   Now for showing Student information to the user there is need to add a view so for that right click on StudentDetail method you will see view window from there you click on Strongly type view and from there dropdown you select you modal class means in my case it is Student, if in your dropdown you are not able to see this modal class then you need to build your application first and then you add a view, after selecting this modal class click on add.


4.   Now we want to show the student detail in a table with label so write following code.
@model MvcApplication1.Models.Student

@{
    ViewBag.Title = "StudentDetail";
}

<h2>StudentDetail</h2>

<table style="font-family:Arial">
    <tr>
        <td>
            Student ID:
        </td>
        <td>
            @Model.StudentId
        </td>
    </tr>
    <tr>
        <td>
            Student Name:
        </td>
        <td>
            @Model.StudentName
        </td>
    </tr>
    <tr>
        <td>
            Gender:
        </td>
        <td>
            @Model.Gender
        </td>
    </tr>
    <tr>
        <td>
            Student School:
        </td>
        <td>
            @Model.StudentSchool
        </td>
    </tr>
</table>


5.   Now in this condition if we Run the application and navigate to http://localhost/MvcApplication1/student/StudentDetail. We should get the output as expected.  it will give error (as null reference)  because  it is not able to find the value of student properties  , In view modal object expecting StudentDetail information but we are not passing these value so pass the student values to view in controller class,
    return View(_student);


6.   Now run your application and navigate to particular URL “http://localhost/MvcApplication1/student/StudentDetail” we will get expected result.



7.   Here if we don’t want to type this URL the  we need to change Controller name and Action  name in RouteConfig.cs File(Available in App_Start folder).
public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Student", action = "StudentDetail", id = UrlParameter.Optional }
            );
        }



C# program Selection Sorting

Selection sort is a straightforward sorting algorithm. This algorithm search for the smallest number in the elements array and then swap i...