MVC3中的包装类

时间:2012-06-13 19:56:48

标签: asp.net-mvc-3 sql-server-2008

我想创建一个包装类,以便所有查询都不应该在控制器中。目前,选择查询放在Controller中。但我想创建另一个抽象层。

我已经创建了一个viewmodel类。但是包装类是另一回事。

我该怎么做?

1 个答案:

答案 0 :(得分:2)

我不直接在我的控制器中进行任何查询。我有一个服务层,我的控制器会调用它,每个服务层都会调用存储库来插入,更新或删除数据或带回数据。

下面的示例代码使用ASP.NET MVC3Entity Framework code first。让我们假设您想要恢复所有国家/地区,并在控制器/视图中出于任何原因使用它:

我的数据库上下文类:

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

我的国家/地区存储库类:

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

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

我的服务层调用我的存储库:

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();
     }
}

我的控制器将调用我的服务层:

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();
     }
}

互联网上有很多关于如何获取数据并显示,插入,编辑等的信息。一个好的起点是http://www.asp.net/mvc。通过他们的教程,它会对你有好处。一切顺利。