SIGN UP MEMBER LOGIN:    
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 trying to illustrate how to use Microsoft enterprise library data using MVC 2 pattern.

MVC - known as Model, Views Controller that separates the modelling of 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 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, 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

Image1.

You can create unit test project if you want.

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

MVC2.gif

Image2.

MVC3.gif

Image3.

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

MVC4.gif

Image4.

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, which is for content support files? This folder contains the cascading style sheet (.css file) for the application. 
  2. Controllers, which is for 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, which is for data-model files such as LINQ-to-SQL .dbml files or data-entity files.
     
  4. Scripts, which is for script files, such as those that support ASP.NET AJAX and jQuery.
     
  5. Views, which is for view page files. This folder contains three subfolders: Account, Home, and Shared. The Account folder contains views that are used as 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 the reference of Microsoft.Practices.EnterpriseLibrary.Data.dll

Add config section in configuration file.

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

Here is 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 in Controller folder

MVC5.gif

Image5.

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 Tab in master page menu:

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

MVC6.gif

Image6.

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 other good solution then share with us. 

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

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
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
    Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor