I'm trying to get an understanding of how to structure an ASP.Net MVC2 Web App using repositories.
A lot of examples, tutorials and books I have read structure the App like so:
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());
}
}
One thing I don't understand is why the Linq query lives in the controller.
I'd like to know why doing something like this is not correct:
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));
}
}