Wrapper class in MVC3

I want to create a wrapper class so that all queries should not be in controller. Currently select queries are placed in Controller. But I want to create another layer for abstraction.

I already created a viewmodel class. But wrapper class is something else.

How do I do that?

Answers


I don't do any queries directly in my controllers. I have a service layer which my controller would call, and each service layer would do a call to the repository to insert, update or delete data or bring back data.

The sample code below uses ASP.NET MVC3 and Entity Framework code first. Lets assume you want to bring back all the countries and use it for whatever reason in your controller/view:

My database context class:

public class DatabaseContext : DbContext
{
     public DbSet<Country> Countries { get; set; }
}

My country repository class:

public class CountryRepository : ICountryRepository
{
     DatabaseContext db = new DatabaseContext();

     public IEnumerable<Country> GetAll()
     {
          return db.Countries;
     }
}

My service layer that calls my repository:

public class CountryService : ICountryService
{
     private readonly ICountryRepository countryRepository;

     public CountryService(ICountryRepository countryRepository)
     {
          // Check for nulls on countryRepository

          this.countryRepository = countryRepository;
     }

     public IEnumerable<Country> GetAll()
     {
          // Do whatever else needs to be done

          return countryRepository.GetAll();
     }
}

My controller that would call my service layer:

public class CountryController : Controller
{
     private readonly ICountryService countryService;

     public CountryController(ICountryService countryService)
     {
          // Check for nulls on countryService

          this.countryService = countryService;
     }

     public ActionResult List()
     {
          // Get all the countries
          IEnumerable<Country> countries = countryService.GetAll();

          // Do whatever you need to do

          return View();
     }
}

There are lots of info on the internet on how to get you data and display it, inserting, editing, etc. A good place to start is at http://www.asp.net/mvc. Work through their tutorials, it will do you good. All the best.


Need Your Help

Java return doesn't output message

java methods return

Question number : I don't understand why when I call this method in main(), it won't output the calculated average. The compiler leaves a blank and that is it. Self-learning Java is challenging.