ARTICLE

Data Access Application Block Using MVC 2 Pattern

Posted by Raj Kumar Articles | ASP.NET MVC with C# July 21, 2010
In this article I am trying to illustrate how to use Microsoft enterprise library data using MVC 2 pattern.
Reader Level:

Introduction

In this article I am attempting to illustrate how to use Microsoft Enterprise Library data using the MVC 2 pattern.

Model, Views Controller (MVC) separates the modelling of the domain, the presentation and the actions based on user input into three classes.

  1. Model: The model manages the behaviour and data of the application domain, responds to requests for information about its state (usually from the view), and responds to instructions to change state (usually from the controller). 
  2. Controller: The controller interprets the mouse and keyboard inputs from the user, informing the model and/or the view to change as appropriate.
     
  3. View: The view manages the display of information.
DAAB: The Data Access Application Block encapsulates the performance and resource management best practices for accessing Microsoft SQL Server databases. It can easily be used as a building block in your own .NET-based application. If you use it then you will reduce the amount of custom code you need to create, test, and maintain.

You can download DAAB from here: http://www.microsoft.com/downloads/details.aspx?familyid=f63d1f0a-9877-4a7b-88ec-0426b48df275&displaylang=en

Getting Started

Make a new project using Visual Studio 2010 and select "ASP.NET MVC 2 Web Application".

MVC1.gif

Image 1.

You can create a unit test project if you want to.

Note: If you are using the Standard or Express editions of Visual Studio then the Create Unit Test Project dialog box is not displayed. Instead, the new MVC application project is generated without a test project.

MVC2.gif

Image 2.

MVC3.gif

Image 3.

The Unit test project has already added the reference of the web project.

MVC4.gif

Image 4.

The folder structure of an MVC project differs from that of an ASP.NET Web site project. The MVC project contains the following folders:
  1. Content for content support files. This folder contains the Cascading Style Sheet (.css file) for the application. 
  2. Controllers for the controller files. This folder contains the application's sample controllers, which are named AccountController and HomeController. The AccountController class contains login logic for the application. The HomeController class contains logic that is called by default when the application starts.
     
  3. Models for the data-model files such as LINQ-to-SQL .dbml files or data-entity files.
     
  4. Scripts for the script files, such as those that support ASP.NET AJAX and jQuery.
     
  5. Views for the view page files. This folder contains three subfolders: Account, Home, and Shared. The Account folder contains views that are used as the UI for logging in and changing passwords. The Home folder contains an Index view (the default starting page for the application) and an about page view. The Shared folder contains the master-page view for the application.
First of all you need to add a reference for "Microsoft.Practices.EnterpriseLibrary.Data.dll".
Then add a config section in the configuration file.

<configSections>
<
sectionname="dataConfiguration
type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data" />
</configSections>

Here is the connection string:

<connectionStrings>
<
addname="NorthWNDConnectionStringconnectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|NORTHWND.MDF;User Instance=true"
providerName="System.Data.SqlClient" />
<addname="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
</connectionStrings>

Now add a controller class to the Controller folder, as in the following:

MVC5.gif

Image 5.

CustomerController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCUsingDAAB.Controllers
{
public class Default1Controller : Controller
    {
//
// GET: /Default1/

public ActionResult Index()
        {
return View();
        }
 
    }
}


Add a Tab to the master page menu:

<li><%:Html.ActionLink("Customers", "Index", "Customer")%></li>

MVC6.gif

Image 6.

Let me copy my models classes code first:

Models/Customer.cs

using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace MVCUsingDAAB.Models
{

public class Customers
    {
///<summary>
///
Gets the CustomerID.
///</summary>
public string CustomerID { get; set; }
///<summary>
///
Gets the CompanyName.
///</summary>
public string CompanyName { get; set; }
///<summary>
///
Gets the ContactName.
///</summary>
public string ContactName { get; set; }
///<summary>
///
Gets the Address.
///</summary>
public string Address { get; set; }
///<summary>
///
Gets the City.
///</summary>
public string City { get; set; }  

public Customers(string id, stringcompanyname, stringcontactname, string address, string city)
        {
CustomerID = id;
CompanyName = companyname;
ContactName = contactname;
            Address = address;
            City = city;
        }
public Customers()
        {
        }
 
    }
}


Models/CustomerModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MVCUsingDAAB.Models
{
interface ICustomerModel
    {
List<Customers>GetCustomers();
    }
}

Models/CustomerListContainerViewModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcContrib.Pagination;
using MvcContrib.UI.Grid;
using System.Data;

namespace MVCUsingDAAB.Models
{
public class CustomerListContainerViewModel
    {
public IPagination<Customers>CustomerPagedList { get; set; }
    }
}


Models/ICustomerModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MVCUsingDAAB.Models
{
interface ICustomerModel
    {
List<Customers>GetCustomers();
    }
}

Models/CustomerListContainerViewModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
usingSystem.Text;

namespace MVCUsingDAAB.Models
{
interface ICustomerModel
    {
List<Customers>GetCustomers();
    }
}


Controller/CustomerController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Configuration;
using System.Data;
using System.Data.Common;
using MVCUsingDAAB.Models;
using MvcContrib.Pagination;

namespace MVCUsingDAAB.Controllers
{
public class CustomerController : Controller
    {       
//
// GET: /Customer/
ICustomerModel customerRepository;
public CustomerController()
        {
customerRepository = newCustomerModel();
        }
public ActionResult Index(int? page)
          {
var customerPagedList = customerRepository.GetCustomers().AsPagination(page ?? 1, 10);
var customerListContainer = new CustomerListContainerViewModel
              {
CustomerPagedList = customerPagedList,
              };
 
return View(customerListContainer);
          }

    }
}

Views/AllCustomers.ascx

<%@ControlLanguage="C#" Inherits="System.Web.Mvc.ViewUserControl<MVCUsingDAAB.Models.CustomerListContainerViewModel>"%>
<%
@ImportNamespace="MvcContrib.UI.Grid"%>
<%
@ImportNamespace="MVCUsingDAAB.Models"%>
<%
@ImportNamespace="MvcContrib.UI.Grid.ActionSyntax"%>
<%
=Html.Grid(Model.CustomerPagedList).AutoGenerateColumns()
    .Columns(column => {
column.For(a =>Html.ActionLink("Details", "Details", new { id = a.CustomerID })).InsertAt(0).Encode(false);
    })   
    .Attributes(@class =>"table-list")
%>

Views/Shared/Page.ascx

<%@ControlLanguage="C#"Inherits="System.Web.Mvc.ViewUserControl<MvcContrib.Pagination.IPagination>"%>
<%
@ImportNamespace="MvcContrib.UI.Pager"%>
<p/>
<%=Html.Pager(Model)
        .First("First")
        .Last("Last")
        .Next("Next")
        .Previous("Previous")
%>
<p/>

Views/Index.aspx

<%@PageTitle=""Language="C#" MasterPageFile="~/Views/Shared/Site.Master" 
Inherits="System.Web.Mvc.ViewPage<MVCUsingDAAB.Models.CustomerListContainerViewModel>"%>
<asp:ContentID="Content1"ContentPlaceHolderID="TitleContent"runat="server">
       Index
</asp:Content>
<
asp:ContentID="Content2"ContentPlaceHolderID="MainContent"runat="server">
<
h2>Customers</h2>
<%Html.RenderPartial("AllCustomers", Model); %>
<%Html.RenderPartial("Pager", Model.CustomerPagedList); %>
</asp:Content>

Now build the project and see the result like this:

7.jpg

Summary

In this article I tried to show how to use Data Access Application Block using MVC 2 Pattern. If you have any questions or comments then drop me a line in www.c-sharpcorner.com comments section or if you have another good solution then share with us. 

Login to add your contents and source code to this article
post comment
     

Guys i can not find the source code of this article because it's too old. But i can solve the issues please tell me wat errors are you facing.

Posted by Raj Kumar May 19, 2013

I know that this is very old post. But still I has importance. Like What James said ,I am also saying this code is really very confusing. I am getting error after error. I am soorry to say this. When you post codes, Please consider others are beginers. The advantage is that All persons who read the code will understand. Please please do not try to post with errors. I tried my best to correct it. I am getting error after error. This may due to my lack of understanding. Some one post code to make others think of him that he is an expert. Please do not follwo their path. Here we all are just students. Just by looking into you code anyone will find out even some syntax error. Please help us. We spending a big part of our time to understand the code first. If you had commented it porperly we could save time. Please post a working code Thanks Sen

Posted by Sen Mathew May 19, 2011

After looking deep into your code. I got few questions. Well I can see it says implementation of DAAB but I am bit confused in figuring out where actually have you implemented functionality of DAAB.

Secondly Models/ICustomerModel.cs and Models/CustomerModel.cs both files seems to be the same I think CustomerModel.cs is the file with an implementation of GetCustomers() function where you got the real use of DAAB.

Please Guide me and also provide a downloadable copy of your code if you can.

Thanks.

Posted by moneem raza Sep 28, 2010

Hi Raj,

I love these articles - MVC is a powerful tool, but there are many concepts that I cannot get my head around.  Taking your example above, how would you add a search facility to the app searching for say company name or City?  I find this very confusing, and have reverted to using a jQuery datatable tool.

Do you have suggestions?

regards,
James

Posted by James Lawrence Jul 30, 2010
COMMENT USING
PREMIUM SPONSORS
DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and add new content to existing PDF documents from within your applications.
Join a Chapter
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Join a Chapter