我将翻译如何使用存储库构建ASP.Net MVC2 Web应用程序的结构。许多示例、教程和书籍都采用以下方式构建应用程序:
public interface IProductsRepository
{
IQueryable<Product> Products { get; }
}
public class SqlProductsRepository : IProductsRepository
{
public Table<Product> productsTable;
public IQueryable<Product> Products
{
get { return productsTable }
}
}
public class ProductsController : Controller
{
IProductsRepository productsRepository;
public ProductsController(IProductsRepository productsRepository)
{
// set the Repository
}
public ActionResult GetLatestPublishedProducts(int pageSize, int page, ref int totalItemCount)
{
// Do LINQ query
return View(from p in productsRepository
where p.PublishedOn != null
orderby p.ProductId descending
select to(p))
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToList());
}
}
我不明白的一件事是为什么Linq查询要放在控制器中。
我想知道为什么这样做是不正确的:
public class SqlProductsRepository : IProductsRepository
{
// set data model stuff here
public List<Product> GetLatestPublishedProducts(int pageSize, int page, ref int totalItemCount) {
// DO LINQ Query in here
}
}
public class ProductsController : Controller
{
// set repository stuff here
public ActionResult GetLatestPublishedProducts(int pageSize, int page, ref int totalItemCount)
{
return View(productsRepository.GetLatestPublishedProducts(pageSize, page, totalItemCount));
}
}