As I mentioned in my last post, I am going to dive deep into ASP.NET web development. I have watched several video tutorials including Introduction to ASP.NET MVC by Christopher Harrison and Jon Galloway and Implementing Entity Framework with MVC.
One thing that I really like about ASP.NET so far is that Visual Studio is able to generate code for me which I would have to write repeatedly by myself. A feature called Scaffolding creates a Controller and several Views on basis of a model.
How does this feature work and how can we tell Visual Studio to generate the desired code for us? I’m going to tell you about it in this post.
Furthermore, I have come across some common errors that stopped me from generating the desired code. I also want to help anyone struggling with this feature to be successful.
How do I use scaffolding in an ASP.NET MVC application?
There are two prerequisites that we need to provide:
- We need a model class which acts as the basis for code generation
- We need EntityFramework installed in our project
- We need a DbContext class
First of all, you need to create a model class. A model represents the data in the MVC (model, view, controller) pattern. In this post, I am going to use a Person model implemented like this:
PersonModel.cs
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace WebApplication1.Models { public class PersonModel { [Key] public int PersonID { get; set; } public string LastName { get; set; } public string FirstName { get; set; } public DateTime Birthday { get; set; } } }
After creating your model, we need to implement a DbContext class for our project. In this case, I made it simple, because the DbContext is not the main topic of this article:
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; using WebApplication1.Models; namespace WebApplication1.DataAccess { public class WebApplication1DbContext : DbContext { public DbSet<PersonModel> Persons { get; set; } } }
When both our model and our data context classes are implemented, we can go to the Solution Explorer and open the context menu on the Controllers folder of our solution:
On the next screen, we can choose what we want to generate. We select the MVC 5 Controller with views, using Entity Framework option:
Finally, we arrive at the Add Controller dialog where we can fill in the model class and the data context class we implemented before. Make sure to select a model and a data context class. Otherwise, the Add button of the dialog won’t be enabled and you cannot click it.
Visual Studio starts scaffolding when we click on the Add button and may successfully generate the code for our Controller and Views.
If there is a problem while the process is taking place, and there are chances, jump to the last section of this post where I write about common problems that occur while scaffolding.
Generated artefacts
The generated controller contains code for creating, editing, deleting and listing Person objects. With just a simple click in the scaffolding dialog, we have a full-featured CRUD controller.
Furthermore, Visual Studio generated the corresponding View to our Controller. There are the following Razor syntax views generated: Create.cshtml, Delete.cshtml, Details.cshtml, Edit.cshtml, Index.cshtml.
Just to show what a generated View looks like I show a screenshot of the Create.cshtml here:
Source code
You can find the complete ASP.NET MVC project for download here. It contains all the code shown above and runs after downloading the required packages from NuGet.
Common problems
The Add button in the Add Controller dialog remains disabled
The dialog does not communicate what the required fields are. We have to fill in a model class and a data context class. If we don’t provide one of those values, the Add button won’t be enabled.
Error: There was an error running the selected code generator: Try rebuilding the project
If we get the following error message, we are told the rebuild the project. This is odd because when we open up the dialog again, we have to fill in all the fields again. So make sure you always build your project before you try to scaffold your model into Views and Controllers.
Error: EntityType ‘PersonModel’ has no key defined. Define the key for this EntityType.
Another common error is the following:
When we face this error, it means that we don’t provide an “ID” column for our model. In the example above, I named my key field “PersonID”. If I want to do so, I have to add the KeyAttribute to the property to tell the system that this property should be the key field of the model.
[Key] public int PersonID { get; set; }
Conclusion
Scaffolding is a powerful concept provided by Visual Studio which speeds up development and helps following design guidelines at the same time. I have used it since I started developing for ASP.NET MVC 5 and it helps me a lot.
At least with Visual Studio 2013 Update 4, there are a few things which could be improved. Anyway, I recommend trying it and see if it helps.
Hi, I have a question about Scaffolding , when i tried to create a new controller, visual studio comunity 2015 shows me “Exception has been thrown by the target of an invocation”. How I can solve it?. Thanks
I have the same problem. something new about that?
The only solution I can think of for the moment is to make sure that you both use the newest updates on your Visual Studio and if possible switch to Visual Studio 2017.
Hi,
I created a .net core app using individual user accounts. Then I did an initial migration to the database. In the database I created the ERD’s and tables. I scaffolded them to the project. So far so good. But if I use the option “Add Controller” I get the error:
There was an error running the selected code generator:
‘Instance of type
ExamResults_SBB.Models.ExamsLibrary.ExamsLibraryDbContext could not be cast to DbContext
at
Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.b__6_0()
at
Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(string[] args)
at
Microsoft.VisualStudio.Web.CodeGeneration.CodeGenCommand.Execte(String[] args)’
Have you got any clue how to solve this?
Hi Michels,
Thanks for your comment. I personally haven’t seen this error. I suggest trying all of the advice posted on this stackoverflow question: http://stackoverflow.com/questions/23910162/scaffolding-controller-doesnt-work-with-visual-studio-2013-update-2.
Let me know if this works out for you. If not, please open a separate question in stackoverflow and post a link to it in the comments on this blog so that future viewers have a link to your stackoverflow thread.
Hi Claudio
Thanks for the post, in my case I was able to fix the problem of exception generated when trying to save a new entry, or save an edit to a record (in my application).
– I have to delete and re-create the Edit View. And the save edit feature worked in my application.
– As for the create new entry, I also re-create the Create View, but had to remove the text box that request the primary key id, the database auto generate the primary key, so when I send another id the application breaks.
In my case, I thought that the problem is due to an update I made in the myappModel.edmx diagram. (I removed an entity that I have added by mistake, and re-added the correct one.) maybe that was the reason that I had to re-generate the Edit view using scaffolding.
Hi Claudio
First of all thanks for the post. I want to ask you about a problem I encounter.
I have a model (A) consist of two other models (B & C). When I try Adding a controller through the “MVC Controller with views, using Entity Framework” option , aka scaffolding, in VS2017 it creates a controller with the corresponding views though it binds only the properties of model A and not the properties of B & C. Is there a way to fix this or do I have to bind the rest on my own?