I want to make sure I'm following industry standards and best practices with my first real crack at MVC. In this case, it's ASP.NET MVC, using C#.
I will be using Entity Framework 4.1 for my model, with code-first objects (the database already exists), so there will be a DBContext object for retrieving data from the database.
In the demos I've gone through on the asp.net website, controllers have data access code in them. This doesn't seem right to me, especially when following the DRY (don't repeat yourself) practices.
For example, let's say I am writing a web application to be used in a public library, and I have a controller for creating, updating, and deleting books in a catalog.
Several of the actions may take an ISBN and need want to return a "Book" object (note this is probably not 100% valid code):
public class BookController : Controller
{
LibraryDBContext _db = new LibraryDBContext();
public ActionResult Details(String ISBNtoGet)
{
Book currentBook = _db.Books.Single(b => b.ISBN == ISBNtoGet);
return View(currentBook);
}
public ActionResult Edit(String ISBNtoGet)
{
Book currentBook = _db.Books.Single(b => b.ISBN == ISBNtoGet);
return View(currentBook);
}
}
Instead, should I actually have a method in my db context object to return one Book? That seems like it is a better separation to me, and helps promote DRY, because I might need to get a Book object by ISBN somewhere else in my web application.
public partial class LibraryDBContext: DBContext
{
public Book GetBookByISBN(String ISBNtoGet)
{
return Books.Single(b => b.ISBN == ISBNtoGet);
}
}
public class BookController : Controller
{
LibraryDBContext _db = new LibraryDBContext();
public ActionResult Details(String ISBNtoGet)
{
return View(_db.GetBookByISBN(ISBNtoGet));
}
public ActionResult Edit(ByVal ISBNtoGet as String)
{
return View(_db.GetBookByISBN(ISBNtoGet));
}
}
Is this a valid set of rules to follow in the coding of my application?
Or, I guess a more subjective question would be: "is this the right way to do it?"