The following example is taken from the book Pro ASP.NET MVC 4 - Adam Freeman
. This book does a good job going over the basics of the MVC framework. In it a database is created from a Product
class (this is the only table in the database in this example). Using the repository and DI (probably not, possibly relevant to this question). Here's the code-first, full on repository implementation. Visual Studio 2010, EF 5 ASP.NET 4.0
`Abstract Folder`
public interface IProductRepository
{
IQueryable<Product> Products { get; }
}
`Concrete Folder`
public class EFDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
}
public class EFProductRepository : IProductRepository
{
private EFDbContext context = new EFDbContext();
public IQueryable<Product> Products
{
get { return context.Products; }
}
}
`Entities Folder`
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
}
I have a ProductController which looks like:
private IProductRepository _repository;
public ProductController(IProductRepository repository)
{
_repository = repository;
}
public ActionResult List()
{
return View(_repository.Products);
}
This works all well and good, the DI is done (not shown) and the controller simply takes an IProductRepository interface type and passes that data to the view for rendering.
I don't understand how this can be done with the database-first approach. All of the tables (only one in this case) live inside SportsStoreContext
in my project. Let's say there are 10 tables in my database, each properties of my SportsStoreContext model. If I have a product controller, do I really need to pass an instance of the entire database context to it?
Here's an incorrectly working version I tried to mock up for my database-first approach:
public class EFDbContext : SportsStoreContext
{
public DbSet<Product> Products { get; set; }
}
public class ProductController : Controller
{
//what type should this be?
private EFDbContext context;
public ProductController()
{
//cant convert SportsStoreContext to EFDbContext
this.context = new SportsStoreContext();
}
public ActionResult List()
{
return View();
}
}
Obviously in real life, I'll have multiple tables in my project, and in my case the database already exists. Can someone point me in the right direction on using the repository pattern with a database-first approach in EF?