Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

Part 11 - Using business objects as model in mvc

Suggested Videos 
Part 8 - Data access in MVC using entity framework
Part 9 - Generate hyperlinks using actionlink html helper
Part 10 - Working with multiple tables in MVC



In this video, we will discuss using business objects as model. Until now, we have been using entity framework and entities. Entities are mapped to database tables, and object relational mapping tools like Entity Framework, nHibernate, etc are used to retrieve and save data. Business objects contain both state(data) and behaviour, that is logic specific to the business.



In MVC there are several conventions that needs to be followed. For example, controllers need to have the word controller in them and should implement IController interface either directly or indirectly. Views should be placed in a specific location that MVC can find them. 

public class HomeController : Controller
{
    public ViewResult Index()
    {
        ViewData["Countries"] = new List<string>()
        {
            "India",
            "US",
            "UK",
            "Canada"
        };

        return View();
    }
}

The following URL will invoke Index() action method with in the HomeController. Notice that our HomeController inherits from base Controller class which inturn inherits from ControllerBase class. ControllerBase inturn inherits from IController class.
http://localhost/MVCDemo/Home/Index

return View() statement with in the HomeController by default looks for a view with name = "Index" in "/Views/Home/" and "/Views/Shared/" folders. If a view with name = "Index" is not found, then, we get an error stating
The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Home/Index.aspx
~/Views/Home/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
~/Views/Home/Index.cshtml
~/Views/Home/Index.vbhtml
~/Views/Shared/Index.cshtml
~/Views/Shared/Index.vbhtml

But with models, there are no strict rules. Infact "Models" folder is optional and they can live anywhere. They can even be present in a separate project.

Let's now turn our attention to using business objects as model. We will be using table "tblEmployee" for this demo. Use the sql script to create and populate this table.

Create table tblEmployee
(
Id int Primary Key Identity(1,1),
Name nvarchar(50),
Gender nvarchar(10),
City nvarchar(50),
DateOfBirth DateTime
)

Insert into tblEmployee values('Mark','Male','London','01/05/1979')
Insert into tblEmployee values('John','Male','Chennai','03/07/1981')
Insert into tblEmployee values('Mary','Female','New York','02/04/1978')
Insert into tblEmployee values('Mike','Male','Sydeny','02/03/1974')
Insert into tblEmployee values('Scott','Male','London','04/06/1972')

Stored procedure to retrieve data 
Create procedure spGetAllEmployees
as
Begin
Select Id, Name, Gender, City, DateOfBirth
from tblEmployee
End

Step 1: Create an ASP.NET MVC 4 Web application with name = MVCDemo

Step 2: Add a Class Library project with Name="BusinessLayer"

Step 3: Right click on the BusinessLayer class library project, and add a class file with name = Employee.cs.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BusinessLayer
{
    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public string City { get; set; }
        public DateTime DateOfBirth { get; set; }
    }
}

Step 4: Right click on the "References" folder of the "BusinessLayer" class library project, and add a reference to "System.Configuration" assembly.

Step 5: Right click on the BusinessLayer class library project, and add a class file with name = EmployeeBusinessLayer.cs.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace BusinessLayer
{
    public class EmployeeBusinessLayer
    {
        public IEnumerable<Employee> Employees
        {
            get
            {
                string connectionString =
                    ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;

                List<Employee> employees = new List<Employee>();

                using (SqlConnection con = new SqlConnection(connectionString))
                {
                    SqlCommand cmd = new SqlCommand("spGetAllEmployees", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    con.Open();
                    SqlDataReader rdr = cmd.ExecuteReader();
                    while (rdr.Read())
                    {
                        Employee employee = new Employee();
                        employee.ID = Convert.ToInt32(rdr["Id"]);
                        employee.Name = rdr["Name"].ToString();
                        employee.Gender = rdr["Gender"].ToString();
                        employee.City = rdr["City"].ToString();
                        employee.DateOfBirth = Convert.ToDateTime(rdr["DateOfBirth"]);

                        employees.Add(employee);
                    }
                }

                return employees;
            }
        }
    }
}

Step 6: Right click on the "References" folder of the "MVCDemo" project, and add a reference to "BusinessLayer" project.

Step 7: Include a connection string with name = "DBCS" in Web.Config file
  <add name="DBCS" 
        connectionString="server=.; database=Sample; integrated security=SSPI"
        providerName="System.Data.SqlClient"/>

Step 8: Right click on the "Controllers" folder and add Controller with name = "EmployeeController.cs".
public class EmployeeController : Controller
{
    public ActionResult Index()
    {
        EmployeeBusinessLayer employeeBusinessLayer =
            new EmployeeBusinessLayer();

        List<Employee> employees = employeeBusinessLayer.Employees.ToList();
        return View(employees);
    }
}

Step 9: Right click on the Index() action method in the "EmployeeController" class and select "Add View" from the context menu. Set
View name = Index
View engine = Razor
Select "Create a strongly-typed view" checkbox
Scaffold Template = List
Click "Add" button

Run the application and navigate to http://localhost/MVCDemo/Employee/Index. The output should be as shown below.
Using business objects as model in mvc

24 comments:

  1. Thank you so much for posting video soon based on my request.

    ReplyDelete
  2. Again I must say your approach to the teaching of MVC is really Excellent. You are the Julie Lerman of MVC. Please take that as a compliment of your grasp of all things including ADO, C sharp, ASP.Net, SQL Server etc. You deliver your lectures with with great details.Thank You.
    In this video 11 you created a EmployeeBusiness layer and mentioned about business rules and validation. Please can you elaborate. I have come across authors mention about this separation of layers and business rules but they never seem to actually show it but stick to simple example. Would it be possible to make a special video of a real example and show what business rules, validation and business layers are all about.

    ReplyDelete
  3. Error 1 Inconsistent accessibility: property type 'System.Collections.Generic.IEnumerable' is less accessible than property 'BusinessLayer.EmployeeBusinessLayer.Employees' c:\users\anudeep\documents\visual studio 2010\Projects\MvcAppbusiness\BusinessLayer\EmployeeBusinessLayer.cs 13 37 BusinessLayer


    plz help sir

    ReplyDelete
    Replies
    1. make the "Employee" class as public in the BusinessLayer

      Delete
  4. I have been following your videos and they are excellent. Thank you very much.
    Omid

    ReplyDelete
  5. Can you explain in a video how to unit test MVC Application

    ReplyDelete
  6. Hi venkat
    Can u Please Resolve this error
    i have added Four Prjocets to my EmployeeMVC application
    1.BusinessObject
    2.DataAcess
    3.BussinessLayer
    4.DB in this my connection and all ado methods have buided

    In BusinessObject
    namespace BusinessObject
    {
    public class EmployeeBO
    {
    public int Empid { get; set; }
    public string Fname { get; set; }
    public string Lname { get; set; }
    public int Salary { get; set; }
    public string JoinDate { get; set; }
    public string Department { get; set; }
    public int DeptId { get; set; }
    }
    }

    In DataAcess

    namespace DataAcess
    {
    public class EmployeeDA
    {
    public static List EmployeeCollection(int id)
    {
    EmployeeBO Empinfo = null;
    List lst = new List();
    SqlParameter[] param = new SqlParameter[]
    {
    new SqlParameter("@Empid",id)
    };
    using (SqlDataReader dr = DB.Sql.GetDataReader("SP_FetchEmployeeCollection", param, true))
    {
    while (dr.Read())
    {
    Empinfo = new EmployeeBO();
    Empinfo.Empid = Convert.ToInt32(dr["Empid"].ToString());
    Empinfo.Fname = dr["Fname"].ToString();
    Empinfo.Lname = dr["Lname"].ToString();
    Empinfo.Salary =Convert.ToInt32((dr["Salary"]));
    Empinfo.JoinDate = dr["JoinDate"].ToString();
    Empinfo.Department = dr["Department"].ToString();
    Empinfo.DeptId = Convert.ToInt32(dr["DeptId"].ToString());
    lst.Add(Empinfo);
    }
    return lst;
    }

    }
    }
    }

    In BussinessLayer


    namespace BussinessLayer
    {
    public class EmployeeBL
    {
    public static List FetchEmployeeCollection(int id)
    {

    return EmployeeDA.EmployeeCollection(id);
    }
    }
    }
    then I have Add a controller name EmployeeController

    namespace EmployeeMVC.Controllers
    {
    public class EmployeeController : Controller
    {
    //
    // GET: /Employee/

    public ActionResult Index()
    {
    List emplist = EmployeeBL.FetchEmployeeCollection(0);
    return View(emplist);
    }

    }
    }

    after buiding my project i add a view

    View name : Index
    View Engine:Razor
    after checked checkbox i have added a model class : EmployeeBO (BusinessObject)
    then Scaffold template list then add

    finaly when i put breakpoint on controller it fetch collection of employees but then error comes out

    Compiler Error Message: CS0103: The name 'model' does not exist in the current context
    Line 1: @model IEnumerable
    Line 2:
    Line 3: @{

    ReplyDelete
  7. hi all ,please let me know why we use public ienumerable employee property in the above code

    ReplyDelete
    Replies
    1. One uses Enumerable to loop through the resultset (List<>) to present the result in the View. In your list view you will create a view which is IEnumerable either manually or by selecting a template. Hope this helps.

      Delete
  8. Inconsistent accessibility: property type 'System.Collections.Generic.IEnumerable' is less accessible than property 'BusinessLayer.EmployeeBusinessLayer.Employees'
    error is coming at the time of build plz help

    ReplyDelete
    Replies
    1. Have you checked to see if the method that you have declared is public?

      Delete
    2. The Employees class most probably is not declared public. This probably led to BO's Employees property to be less assessible than public.
      Also ensure that public properties (here Employees) is put within the PUBLIC Class(Here, EmployeeBusinessLayer)
      =>Rule: The accessibility of a class should be greater than its members accessibility.

      Delete
  9. Please solved this error in given code.
    SqlDataReader rdr = cmd.ExecuteReader();

    An unhandled exception of type 'System.StackOverflowException' occurred in System.Data.dll

    Thanks

    ReplyDelete
  10. Hi Guys I am new to MVC.. Please help me.

    Not able to add "EmployeeBusinessLayer" in my Employee controller.
    What could be the issue. ? What m i missing ? .
    I have implemented the same way its written above.

    Thnx in advance.

    ReplyDelete
  11. You have to add a reference to the EmployeeBusinessLayer project in your MVC projet , and add the using clause in your controller class

    ReplyDelete
  12. @amazigh The project isn't there, its not even adding into the the refrence.

    ReplyDelete
  13. Build the project to see the project in references

    ReplyDelete
  14. Can anybody help me out here i am getting the error in this state.

    //I AM GETTING ERROR AT THIS STAGE



    Line 29: @foreach (var item in Model) {

    ReplyDelete
  15. Hi all,

    i am getting below error.

    can anyone help me to resolve this please.

    The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[BussinessLayer.Test]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[BussinessLayer.TestBussinessLayer]'.

    ReplyDelete
  16. i am getting error at @model IEnumerable

    "The name model does not exist in the current context"

    please help to resolve this error

    ReplyDelete
  17. i am using visual studio 2012. in classliberary i cant use
    configurationmanager and sqlclient property

    ReplyDelete
  18. using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data;
    using System.Data.SqlClient;
    using System.Configuration;
    using System.Collections.Specialized;
    using BuisenessLibrary;
    namespace BusinessLayer
    {
    public class EmployeeBusinessLayer
    {
    public IEnumerable Employees
    {
    get
    {
    string connectionString =
    ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;

    List employees = new List();

    using (SqlConnection con = new SqlConnection(connectionString))
    {
    SqlCommand cmd = new SqlCommand("spGetAllEmployees", con);
    cmd.CommandType = CommandType.StoredProcedure;
    con.Open();
    SqlDataReader rdr = cmd.ExecuteReader();
    while (rdr.Read())
    {
    Employee employee = new Employee();
    employee.EmployeeID = Convert.ToInt32(rdr["Id"]);
    employee.Name = rdr["Name"].ToString();
    employee.Gender = rdr["Gender"].ToString();
    employee.City = rdr["City"].ToString();


    employees.Add(employee);
    }
    }

    return employees;
    }
    }
    }
    }


    ERROR IS:CONFIGURATION manager does not exist in current context

    ReplyDelete
  19. i am using visual studio 2013
    while adding view to index() method
    it dosen't showing class of business layer

    ReplyDelete

If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.