Part 8 Data access in mvc using entity framework
Tags
asp.net mvc database tutorial
asp.net mvc database application tutorial
creating asp.net mvc application with database
asp.net mvc database connection using entity framework
asp.net mvc database project
database connectivity in asp.net mvc
The controller responds to URL request, gets data from a model and hands it over to the view. The view then renders the data. Model can be entities or business objects.
In part 7, we have built Employee entity.
public class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string City { get; set; }
}
In this video, we will discuss, retrieving data from a database table tblEmployee using entity framework. In a later video, we will discuss using business objects as our model.
Step 1: Install entity framework, if you don't have it installed already on your computer. At the time of this recording the latest version is 5.0.0.0. Using nuget package manager, is the easiest way to install. A reference to EntityFramework.dll is automatically added.
Open visual studio - Tools - Library Package Manager - Manage NuGet Packages for Solution
Step 2: Add EmployeeContext.cs class file to the Models folder. Add the following "using" declaration.
using System.Data.Entity;
Copy & paste the following code in EmployeeContext.cs
public class EmployeeContext : DbContext
{
// Replace square brackets, with angular brackets
public DbSet[Employee] Employees {get; set;}
}
EmployeeContext class derives from DbContext class, and is responsible for establishing a connection to the database. So the next step, is to include connection string in web.config file.
Step 3: Add a connection string, to the web.config file, in the root directory.
Step 4: Map "Employee" model class to the database table, tblEmployee using "Table" attribute as shown below.
[Table("tblEmployee")]
public class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string City { get; set; }
}
Note: "Table" attribute is present in "System.ComponentModel.DataAnnotations.Schema" namespace.
Step 5: Make the changes to "Details()" action method in "EmployeeController" as shown below.
public ActionResult Details(int id)
{
EmployeeContext employeeContext = new EmployeeContext();
Employee employee = employeeContext.Employees.Single(x =] x.EmployeeId == id);
return View(employee);
}
Step 6: Finally, copy and paste the following code in Application_Start() function, in Global.asax file. Database class is present "in System.Data.Entity" namespace. Existing databases do not need, database initializer so it can be turned off.
Database.SetInitializer[MVCDemo.Models.EmployeeContext](null);
That's it, run the application and notice that the relevant employee details are displayed as expected.
11
views
Part 7 Models in an mvc application
In this video we will discuss models in an mvc application.
Let's understand models with an example. We want to retrieve an employee information from tblEmployee table and display it in a view.
To encapsulate Employee information, add Employee model class to the Models folder. To do this
1. Right click on "Models" folder - Add - Class
2. Name the class as Employee.cs
3. Click "Add"
Copy and paste the following code in Employee.cs class file.
public class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string City { get; set; }
}
Now let's Add EmployeeController class to "Controllers" folder. To do this
1. Right click on "Controllers" folder - Add - Controller
2. Use EmployeeController as the name
3. Click "Add"
We want to use "Employee" model class in EmployeeController. So copy and paste the following "using" statement in "EmployeeController.cs"
using MVCDemo.Models;
By default an Index() Action method is created in EmployeeController. Change the name of the function to Details(). Create an instance of Employee class. For now we will hard code Employee data in this class. In a later video session, we will discuss about retrieving employee information from the database table tblEmployee. At this point EmployeeController should look as shown below.
public ActionResult Details()
{
Employee employee = new Employee()
{
EmployeeId = 101,
Name = "John",
Gender = "Male",
City = "London"
};
return View();
}
Now, we need to pass the employee model object that we constructed in EmployeeController to a view, so the view can generate the HTML and send it to the requested client. To do this we first need to add a view. To add a view
1. Right click on Details() action method and select "Add View" from the context menu
2. Set
a)View Name = Details
b)View Engine = Razor
c)Select "Create strongly typed view" check box
d)From the "Model class" dropdownlist, select "Employee (MVCDemo.Models)"
Note: If Employee class is not visible in the dropdownlist, please build your project and then try adding the view again.
3. Finally click "Add"
At this point, Details.cshtml should be added to "Employee" folder. Please note that "Employee" folder is automatically created and added to "Views" folder.
At this point if you run the project, and if you navigate to the following URL, you get a runtime error stating - Object reference not set to an instance of an object.
localhost/MVCDemo/Employee/Details
To fix this error, pass "Employee" object to the view. The "return" statement in Details() action method need to be modified as shown below.
return View(employee);
That's it. Run the application and navigate to localhost/MVCDemo/Employee/Details. We should get the output as expected.
3
views
Part 10 Working with multiple tables in mvc
In this video we will discuss working with 2 related tables in MVC
1. tblDepartment
2. tblEmployee
This is what we want to achieve
1. Display all the departments from tblDepartments table. The Department names should be rendered as hyperlinks.
2. On clicking the department name link, all the employees in the department should be displayed. The employee names should be rendered as hyperlinks.
3. On clicking the employee name link, the full details of the employee should be displayed.
4. A link should also be provided on the employee full details page to navigate back to Employee list page. Along the same lines, a link should also be provided on the employee list page to navigate back to Departments list page.
Implementing Departments List:
Step 1: Right click on the "Models" folder and add a class file with name=Department.cs. Copy and paste the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations.Schema;
namespace MVCDemo.Models
{
[Table("tblDepartment")]
public class Department
{
public int ID { get; set; }
public string Name { get; set; }
public List[Employee] Employees { get; set; }
}
}
Step 2: Add "Departments" property to "EmployeeContext" class that is present in "EmployeeContext.cs" file in "Models" folder.
public class EmployeeContext : DbContext
{
public DbSet[Department] Departments { get; set; }
public DbSet[Employee] Employees { get; set; }
}
Step 3: Right click on the "Controllers" folder and add a Controller, with name=DepartmentController. Copy and paste the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCDemo.Models;
namespace MVCDemo.Controllers
{
public class DepartmentController : Controller
{
public ActionResult Index()
{
EmployeeContext employeeContext = new EmployeeContext();
List[Department] departments = employeeContext.Departments.ToList();
return View(departments);
}
}
}
Step 4: Right click on the Index() action method in DepartmentController class and select "Add View" from the context menu. Set
View name = Index
View engine = Razor
Select "Create Strongly-typed view checkbox
Select Department class, from "Model class" dropdownlist
Click "Add" button
Copy and paste the following code in Index.cshtml view file in Department folder
@using MVCDemo.Models;
@model IEnumerable[Department]
[div style="font-family:Arial"]
@{
ViewBag.Title = "Departments List";
}
[h2]Departments List[/h2]
[ul]
@foreach (Department department in @Model)
{
[li]@Html.ActionLink(department.Name, "Index", "Employee",
new { departmentId = department.ID }, null)[/li]
}
[/ul]
[/div]
Changes to Employee List and Detail pages
Add "DepartmentId" propertu to "Employee" model class that is present in Employee.cs file in "Models" folder.
[Table("tblEmployee")]
public class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string City { get; set; }
public int DepartmentId { get; set; }
}
Add "departmentId" parameter to Index() action method in "EmployeeController" class that is present in "EmployeeController.cs" file in "Controllers" folder. Use the "departmentId" parameter to filter the list of employees as shown below.
public ActionResult Index(int departmentId)
{
EmployeeContext employeeContext = new EmployeeContext();
List[Employee] employees = employeeContext.Employees.Where(emp =] emp.DepartmentId == departmentId).ToList();
return View(employees);
}
Copy and paste the following line in "Index.cshtml" that is present in "Employee" folder in "Views" folder. With this change we are able to generate an action link to redirect the user to a different controller action method.
@Html.ActionLink("Back to Department List", "Index", "Department")
6
views
Part 9 Generate hyperlinks using actionlink html helper
In this video we will discuss, generating hyperlinks using actionlink html helper, for navigation between mvc pages.
Please watch Part 8, before proceeding.
We want to display all the employees in a bulletted list as shown below. Notice that all the employee names are rendered as hyperlinks.
Adding Links between pages using html helpers.png
When the hyperlink is clicked, the user will be redirected to employee details page, displaying the full details of the employee as shown below.
Generate links using Html.ActionLink html helper.png
Copy and paste the following Index() action method in EmployeeController class. This method retrieves the list of employees, which is then passed on to the view for rendering.
public ActionResult Index()
{
EmployeeContext employeeContext = new EmployeeContext();
// Replace square brackets with angular brackets
List[Employee] employees = employeeContext.Employees.ToList();
return View(employees);
}
At the moment, we don't have a view that can display the list of employees. To add the view
1. Right click on the Index() action method
2. Set
View name = Index
View engine = Razor
Select, Create a stronlgy-typed view checkbox
Select "Employee" from "Model class" dropdownlist
3. Click Add
At the point, "Index.cshtml" view should be generated. Copy and paste the following code in "Index.cshtml".
@* Replace square brackets with angular brackets *@
@model IEnumerable[MVCDemo.Models.Employee]
@using MVCDemo.Models;
[div style="font-family:Arial"]
@{
ViewBag.Title = "Employee List";
}
[h2]Employee List[/h2]
[ul]
@foreach (Employee employee in @Model)
{
[li]@Html.ActionLink(employee.Name, "Details", new { id = employee.EmployeeId })[/li]
}
[/ul]
[/div]
Points to Remember:
1. @model is set to IEnumerable[MVCDemo.Models.Employee]
2. We are using Html.ActionLink html helper to generate links
Copy and paste the following code in Details.cshtml
@Html.ActionLink("Back to List", "Index")
2
views
Part 6 ViewData and ViewBag in mvc
In this video we will discuss
1. What is ViewData
2. What is ViewBag
3. Difference between ViewData and ViewBag
Both ViewData and ViewBag are used to pass data from a controller to a view. ViewData is a dictionary of objects that are stored and retrieved using strings as keys. The syntax of ViewData is very similar to that of ViewState, SessionState and ApplicationState.
// Storing data in ViewData
ViewData["YourData"] = "SomeData";
// Retrieving data from ViewData
string strData = ViewData["YourData"].ToString();
ViewData does not provide compile time error checking. For example, if you mis-spell the key names you wouldn't get any compile time error. You get to know about the error only at runtime.
ViewBag uses the dynamic feature that was introduced in to C# 4. It allows an object to have properties dynamically added to it. Using ViewBag the above code can be rewritten as below.
// Storing data in ViewBag
ViewBag.YourData = "SomeData";
// Retrieving data from ViewBag
string strData = ViewBag.YourData;
Just like ViewData, ViewBag does not provide compile time error checking. For example, if you mis-spell the property name, you wouldn't get any compile time error. You get to know about the error only at runtime.
Internally ViewBag properties are stored as name/value pairs in the ViewData dictionary.
Please Note: To pass data from controller to a view, It's always a good practice to use strongly typed view models instead of using ViewBag & ViewData. Strongly typed view models provide compile time error checking. We will discuss view models in a later video session.
1
view
Part 5 Views in an mvc application
In this video we will discuss views. Please watch Part 4 of MVC tutorial before proceeding. Let's change the Index() method in HomeController to return a list of country names. Since country names are strings, return List of strings. Get rid of id and name parameters.
Run the application and notice that the output is not as expected.
System.Collections.Generic.List`1[System.String]
To correct this problem, let's add a view to our project.
1. Right click on the Index() function
2. Click on "Add View"
3. Notice that, the view name in "Add View" dialog box matches the name of the controller action method
4. Select "Razor" as the view engine
5. Leave the rest of the defaults as is, and click "Add" button
We will discuss ViewBag & ViewData, and the differences between them in our next video session. For now, understand that, ViewBag & ViewData is a mechanism to pass data from the controller to the view.
Please Note: To pass data from controller to a view, It's always a good practice to use strongly typed view models instead of using ViewBag & ViewData. We will discuss view models in a later video session.
Please Note: We use "@" symbol to switch between html and c# code. We will discuss razor views and their syntax in a later video session.
1
view
Part 4 Controllers in an mvc application
In this video we will discuss about controllers. Please watch Part 3 of MVC tutorial before proceeding. In Part 3, we discussed that, the URL - http://localhost/MVCDemo/Home/Index will invoke Index() function of HomeController class. So, the question is, where is this mapping defined. The mapping is defined in Global.asax. Notice that in Global.asax we have RegisterRoutes() method.
RouteConfig.RegisterRoutes(RouteTable.Routes);
Right click on this method, and select "Go to Definition". Notice the implementation of RegisterRoutes() method in RouteConfig class. This method has got a default route.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
The following URL does not have id. This is not a problem because id is optional in the default route.
http://localhost/MVCDemo/Home/Index
Now pass id in the URL as shown below and press enter. Nothing happens.
http://localhost/MVCDemo/Home/Index/10
Change the Index() function in HomeController as shown below.
public string Index(string id)
{
return "The value of Id = " + id;
}
Enter the following URL and press enter. We get the output as expected.
http://localhost/MVCDemo/Home/Index/10
In the following URL, 10 is the value for id parameter and we also have a query string "name".
http://localhost/MVCDemo/home/index/10?name=Pragim
Change the Index() function in HomeController as shown below, to read both the parameter values.
public string Index(string id, string name)
{
return "The value of Id = " + id + " and Name = " + name;
}
Just like web forms, you can also use "Request.QueryString"
public string Index(string id)
{
return "The value of Id = " + id + " and Name = " + Request.QueryString["name"];
}
2
views
Creating your first aspnet mvc application - Part 3
In this video we will discuss about
1. Creating an asp.net mvc application
2. Understand how mvc request is processed as apposed to webform request
Creating an mvc application:
1. Open visual studio
2. Click File - New Project
3. Select "Web" from "Installed Templates" section
4. Select ASP.NET MVC 4 Web Application
5. Set Name="MVCDemo"
6. Click OK
7. Select "Empty" template. Select "Razor" as the ViewEngine. There are 2 built in view engines - Razor and ASPX. Razor is preferred by most mvc developers. We will discuss about Razor view engine in detail in a later video session.
8. At this point you should have an mvc application created.
Notice that in the solution explorer, you have several folders - Models, Views, Controllers etc. As the names suggest these folders are going to contain Models, Views, and Controllers. We will discuss about Models, Views, and Controllers in a later video session.
Now let's add a controller to our project.
1. Right Click on "Controllers" folder
2. Select Add - Controller
3. Set Controller Name = HomeController
4. Leave rest of the defaults and click "Add"
We should have HomeController.cs added to "Controllers" folder.
At this point run the application by pressing CTRL+F5. Notice that you get an error.
To fix this error, we need to add a view with name, "Index". We will discuss about views in detail in a later video session. Let's fix it another way. The following is the function that is automatically added to HomeController class
public ActionResult Index()
{
return View();
}
Change the return type of Index() function from "ActionResult" to "string", and return string "Hello from MVC Application" instead of View().
public string Index()
{
return "Hello from MVC Application";
}
Run the application and notice that, the string is rendered on the screen. When you run the application, by default it is using built-in asp.net development server. Let's use IIS, to run the application instead of the built-in asp.net development server.
1. In the solution explorer, right click on the project and select "Properties"
2. Click on "Web" tab
3. Select "Use Local IIS Web Server" radio button
4. Notice that the Project Url is set to http://localhost/MVCDemo by default
5. Finally click on "Create Virtual Directory" button
//configuring iis to run mvc application.png
Run the application, and notice that the URL is "http://localhost/MVCDemo/"
Now change the URL to "http://localhost/MVCDemo/Home/index"
In the URL "Home" is the name of the controller and "Index" is the method within HomeController class.
So the improtant point to understand is that the URL is mapped to a controller action method. Where as in web applications, the URL is mapped to a physical file. For example, in a web application, if we have to display the same message.
1. We add a webform and in the Page_load() event include Response.Write("Hello from ASP.NET Web Forms Application");
2. We then access WebForm1.aspx as shown below
http://localhost/WebFormsApplication/WebForm1.aspx
3. The Page load event gets executed and the message string is displayed.
13
views
ASP.NET MVC Part 1 | Step By Step
this my new youtube channel https://youtu.be/8gbjcFIdIoI
please subscribe
In this video we will discuss about installing asp.net mvc. Before installing asp.net mvc, first let's determine what version is already installed. Go to "Control Panel" and click on "Programs and Features".
If you want to create asp.net mvc 3 or 4 applications, then please download and install asp.net mvc 3 and 4 from the following locations.
ASP.NET MVC 3
http://www.asp.net/mvc/mvc3
ASP.NET MVC 4
http://www.asp.net/mvc/mvc4
26
views
What aspnet mvc version is my mvc application using - Part 2
This is my new youtyube channel
https://youtu.be/8gbjcFIdIoI
Please subscribe
In this video we will discuss about, How to determine what version of asp.net mvc is being used by an existing mvc application
There are 2 ways to do this
1. At design time - In the solution explorer, expand "References" folder. Right click on System.Web.Mvc assembly and select "Properties" and you can find the version that's used.
2. At runtime using code - typeof(Controller).Assembly.GetName().Version.ToString()
5
views