Living life by the motto, "You didn't get this far by giving up." It hasn't failed her yet.
Scaffolded code is a great basis for modification, but remember that it's only a starting point.
So you want to make a MVC application. You’ve planned out what it’s going to look like, you’ve chosen a database, you’ve created a new MVC project in Visual Studio and written your models… Now it’s time to put the ‘VC’ in ‘MVC’ by writing some views and controllers, right?
public class Author
{
// Key
public int Id { get; set; }
// Properties
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime Born { get; set; }
public DateTime? Died { get; set; }
// Nav properties
public virtual IEnumerable<Book> Books { get; set; }
}
public class Book
{
// Keys
public int Id { get; set; }
public int AuthorId { get; set; }
// Properties
public string Title { get; set; }
public string? Description { get; set; }
public DateTime Published { get; set; }
// Nav properties
public virtual Author Author { get; set; }
}
Some basic models for demonstration
Well, you certainly could write those yourself, but why not have Entity Framework do some of the heavy lifting for you by scaffolding? Simply right click the Controllers folder, choose Add > New Scaffolded Item, and in the menu that appears, choose MVC Controller with views. Microsoft will ask you what model and database context you want to use, then it will generate a controller with actions and views for basic CRUD (create, read, update, delete) operations. Job well done, time to publish, right? Let's take a look at some of what Entity Framework made for us:
public BooksController(ApplicationDbContext context)
{
_context = context;
}
public async Task<IActionResult> Index()
{
var applicationDbContext = _context.Books.Include(b => b.Author);
return View(await applicationDbContext.ToListAsync());
}
Whoa, absolutely not! Pictured here are the instantiation of the controller and the Index action, and problems are immediately evident. The controller is accessing the database directly, which is a problem if you want to use the repository pattern of loosely coupled code (which you should!). The scaffolded code uses implicit declaration where explicit would be better, the model being fed into the view isn’t sorted in any meaningful way…
So no, scaffolding using Entity Framework isn’t a magic cure-all. It’s a useful tool for creating a base for modification, but at the end of the day, a tool is nothing without someone to use it.
0 Comments