Site Meter
 
 

Scaffold your ASP.NET MVC 3 project with the MvcScaffolding package

This post is part of a series about the MvcScaffolding NuGet package:

  1. This post: Scaffold your ASP.NET MVC 3 project with the MvcScaffolding package
  2. Standard usage: Typical use cases and options
  3. One-to-Many Relationships
  4. Scaffolding Actions and Unit Tests
  5. Overriding the T4 templates
  6. Creating custom scaffolders
  7. Scaffolding custom collections of files

Among many other improvements with ASP.NET MVC 3, we’re keen to make it easier to pick up and start using productively if you’re entirely new to the framework, and to automate common development tasks if you’re experienced and already know what you’re doing.

So, I’ve been working with Scott Hanselman lately on an enhanced new scaffolding package called MvcScaffolding. The term “Scaffolding” is used by many software technologies to mean “quickly generating a basic outline of your software that you can then edit and customise”. The scaffolding package we’re creating for ASP.NET MVC is greatly beneficial in several scenarios:

  • If you’re learning ASP.NET MVC for the first time, because it gives you a fast way to get some useful, working code, that you can then edit and adapt according to your needs. It saves you from the trauma of looking at a blank page and having no idea where to start!
  • If you know ASP.NET MVC well and are now exploring some new add-on technology such as an object-relational mapper, a view engine, a testing library, etc., because the creator of that technology may have also created a scaffolding package for it.
  • If your work involves repeatedly creating similar classes or files of some sort, because you can create custom scaffolders that output test fixtures, deployment scripts, or whatever else you need. Everyone on your team can use your custom scaffolders, too.

Other features in MvcScaffolding include:

  • Support for C# and VB projects
  • Support for the Razor and ASPX view engines
  • Supports scaffolding into ASP.NET MVC areas and using custom view layouts/masters
  • You can easily customize the output by editing T4 templates
  • You can add entirely new scaffolders using custom PowerShell logic and custom T4 templates. These (and any custom parameters you’ve given them) automatically appear in the console tab-completion list.
  • You can get NuGet packages containing additional scaffolders for different technologies (e.g., there’s a proof-of-concept one for LINQ to SQL now) and mix and match them together

It’s currently at a beta level so it is expected to work :) but if you push it in funny ways you might get odd results. Please let me know if you discover issues – I’m sure there’ll be some – so we can tidy it up and make it more robust.

Installation

The short version is this: Install-Package MvcScaffolding. If you understood that, do it and skip ahead to “Scaffolding a CRUD interface”. If not, read on.

1. Install ASP.NET MVC 3, which includes the excellent NuGet Package Manager.

2. Create or open an ASP.NET MVC 3 web application. I’m calling mine ‘SoccerSite’.

3. Install the MvcScaffolding package. You can install it using the NuGet Package Manager Console, so it only takes a few seconds and you don’t have to download anything using your browser.  To do so,

  • Open the Package Manager Console window using Visual Studio’s View->Other Windows->Package Manager Console menu item.
  • Enter the following:
Install-Package MvcScaffolding

image

  • That’s it! Note: be sure you installed MvcScaffolding, not MvcScaffold. We’ll retire the old MvcScaffold package shortly.

In case you’re wondering, EFCodeFirst is the new super-elegant version of Entity Framework that persists plain .NET objects to a relational database without any configuration fuss, T4Scaffolding is the core scaffolding infrastructure (locates types in your project, finds scaffolders in other packages, renders templates, etc), and MvcScaffolding is a set of ASP.NET MVC-specific templates (for controllers and views) that bolts onto the T4Scaffolding core.

Scaffolding a CRUD interface

Let’s create a model for a soccer team. Add the following class to your Models folder, then compile your solution (Ctrl-Shift-B):

namespace SoccerSite.Models
{
    public class Team
    {
        public int TeamId { get; set; }
        [Required] public string Name { get; set; }
        public string City { get; set; }
        public DateTime Founded { get; set; }
    }
}

Next, we can create a complete Create-Read-Update-Delete (CRUD) UI for this model by issuing a single scaffolding command into the Package Manager Console:

Scaffold Controller Team

Note: You can use the TAB key to autocomplete many things in the Package Manager Console. In this case, you can autocomplete the words “Scaffold” and “Controller”, since the scaffolding package knows about them. It doesn’t know about “Team”, though – we may add completion on model type names in a future version.

image

As you can see, it’s gone ahead and created a controller, a database context (a tiny bit of Entity Framework code that represents a data store), and views for all the CRUD actions. You can run it right now (Shift-F5), and as long as you have SQL Server Express running on your machine, EFCodeFirst will automatically connect to it, create your database schema, and you’ve got a basic working application without writing a single line of procedural code.

Note that since the model was called “Team”, the controller is called “TeamController”, so to reach it you need to point your browser to http://…/team:

image

The database is initially empty.

image

Creating an item. Validation rules are applied automatically. Note that since “Founded” is a DateTime it can’t be null and hence is required. Change it to DateTime? (i.e., with the question mark to make it nullable) if you want it to be optional.

image

Listing items

image

Deleting an item

But what if I don’t have SQL Express installed?

If you don’t have SQL Express installed and running, you may have got the following error when your code tried to read or write some data:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Blah blah blah…

No problem! You can quickly switch to use the new SQL Server Compact – a lightweight, in-process database – without having to download or install anything manually. Simply add SQL Server Compact to your project by issuing the following command in the Package Manager Console:

Install-Package EFCodeFirst.SqlServerCompact

Ta da – no more external database required. Run your project again (Shift-F5) and this time it will create and connect to a file-based database (a .sdf file will appear in your ~/App_Data folder). The EFCodeFirst.SqlServerCompact package adds a file to your project called AppStart_SQLCEEntityFramework.cs, which configures the runtime to use SQL CE.

Of course you probably still want the proper version of SQL Server when you eventually deploy your application for public use, but for small applications or for learning, SQL CE is really handy.

Scaffolding a repository

If you check out the code right now, you’ll see that TeamController reads and writes the data in SoccerSiteContext directly. That’s fine in many simple scenarios, but if you want to decouple your controller logic from persistence logic a little (e.g., so that you can write clean unit tests for the controller), you may prefer to reach your data through an interface.

No problem! Let’s regenerate the controller with the –Repository flag:

Scaffold Controller Team –Repository -Force

Notice that we also need to say –Force, otherwise the scaffolder won’t overwrite the files you already have in your project. Now the scaffolder will produce an additional class, TeamRepository, and the following interface which TeamRepository implements:

    public interface ITeamRepository
    {
        void Add(Team post);
        void Delete(int id);
        IEnumerable<team> GetAllTeams();
        Team GetById(int id);
        void Save();
    }

TeamController will now only read and write data using ITeamRepository. If you’re new to ASP.NET MVC it may not be obvious why this is desirable, but if you start trying to write unit tests or switch data access technologies, you’ll find this interface-based data access method to be much cleaner and more flexible.

There’s so much more

It’s not just about CRUD! You can use scaffolding to create any type of project item if you write a template for it. This blog post has covered only the absolute beginning of what you can do, so over the coming days I’ll write blog posts to cover:

  • Scaffolding specific individual items (e.g., views, repositories, etc) rather than whole controllers and related files
  • Getting additional scaffolder packages and controlling which ones are used by default. For example, there’s currently a proof-of-concept LINQ to SQL scaffolding package that you can install and set to act as the default type of repository/data context.
  • Customising the T4 templates that the scaffolders use to generate code
  • Creating entirely new custom scaffolders for new types of things (e.g., unit test fixtures)

184 Responses to Scaffold your ASP.NET MVC 3 project with the MvcScaffolding package

  1. KevDog

    I’ve been playing with the earlier versions with something approaching joy. I do have one feature request, I know that you can add a flag to not overwrite previously generated code that you have made changes to. However, I’d like something more idiot proof, perhaps an attribute that I can add to classes after I’ve twiddled them to keep them from being changed. Of course, if something like this already exists, my bad for missing it.

    Thanks,

    Kevin

  2. Steve

    KevDog – by default we don’t overwrite any files you’ve already created. You have to explicitly pass the “-Force” flag to make it overwrite.

    With that and source control, I reckon you’ll be pretty safe, but let me know if you thing some additional barrier is needed :)

  3. Pingback: Scott Hanselman - ASP.NET MVC3, WebMatrix, NuGet, IIS Express and Orchard released - The Microsoft January Web Release in Context

  4. KevDog

    Ahh…my misunderstanding, I thought it was the other way around. Well, that’s much smarter. I retract my silly comment.

  5. Heber

    Hi Steve. I’m trying to install the MvcScaffolding, but this is not found in NuGet source, just these three previous versions:

    MvcScaffold 0.1
    MvcScaffold 0.2
    MvcScaffold 0.3

    Was the package publish?

    Tks.

  6. Gene

    Shouldn’t controller names be plural? TeamsController vs. TeamController. Can this be customized?

  7. Dave

    The first time I did an F5, I had a permissions issue w/ SqlExpress (regardless of whether I was running VS as an admin. Win7_x86 Ent.ed. BTW). I granted myself sysadmin to SqlExpress. The underlying exception now is the login failed for my user. Ideas?

  8. Dave

    OK, it worked when I added

    DbDatabase.SetInitializer(new DropCreateDatabaseIfModelChanges());

    to the Global.asax.cs file. However my site does not have the usual blue cruft of an MVC site.

  9. Dave

    Wonderful. Now VS is telling me ‘Scaffold’ is not a recognized name of a cmdlet. I even reinstalled the package and restarted VS. Oh boy.

  10. Steve

    Heber – Make sure you’re using “MvcScaffolding”, not “MvcScaffold”.

    Gene – You can customize it. I’ll cover this in an upcoming post.

    Dave – I have seen some issues like that. If you email me we can talk through some steps to diagnose it.

  11. av

    Is this open source available for this? for reading

  12. Matthew

    When you scaffold the ITeamRepository the variable was called post, not sure if that’s copy and paste error or it is the scaffold generating a bad variable name.

  13. Steve

    Matthew – well spotted! The code will work, but clearly that is a crazy variable name. I’ll update the repository template to say something more sensible.

  14. Matthew

    NP Steve, thanks for your hard work and contributions here on the blog.

  15. Saber

    What if I have Entity Data Model only, how can I use MVCScaffolding?

  16. Steve – I ran the example, and it worked fine, but with no styling. The generated pages do not inherit from Site.Master and hence don’t have any .css reference in them. Did I do something wrong?

    Richard

  17. mahmud

    I’m getting this error message:

    PM> Scaffold Controller Team

    The term ‘Scaffold’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, ver
    ify that the path is correct and try again.
    At line:1 char:9
    + Scaffold <<<< Controller Team
    + CategoryInfo : ObjectNotFound: (Scaffold:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

  18. mahmud, I had the same problem yesterday. I managed to solve the problem by uninstalling and reinstalling the MvcScaffolding. That didn’t work at first, but when I uninstalled it using the -RemoveDependencies switch, and then reinstalled it again, everything worked fine again.

    So you can try this:

    Uninstall-Package MvcScaffolding -RemoveDependencies
    Install-Package MvcScaffolding

  19. Steve

    Dave, Mahmud, Kristof – I tracked down an issue that, on some computers, prevents the cmdlets being available after you restart Visual Studio. There’s an updated version (0.8.7) now on NuGet that fixes this. To get the update:

    1. Enter into your package manager console “Update-Package MvcScaffolding”
    2. Then restart Visual Studio

    This should sort it out, but if not, please send me an email.

  20. All I can say is… Schwing!

  21. John

    Seem to be experiencing the unknown cmdlet issue as mahmud.

    Tried typing the package mgr console commands ‘Uninstall-Package MvcScaffolding -RemoveDependencies’ and ‘Install-Package MvcScaffolding’, restarted Visual Studio 2010, but still getting the same error message.

    Wondering what else I could try? thx, John

  22. I get the following error when trying to scaffold my controller:
    PM> Scaffold Controller Story
    Get-PrimaryKey : Cannot find primary key property for type ‘Story’. No properties appear to be primary keys.

    I think it may have to do with the fact that the primary key property is on the superclass. Does that sound right to you? Is there a workaround for this?

  23. Bas Jansen

    It would be nice if the *Repository class and I*Repository interfaces where defined as partial. That way you can add an extra file and put your own methods in it which will never be overwritten.

    ps. I really like this way of building an app.

  24. Rodrigo Caballero

    Simply awesome. I’ll be waiting for the next tutorials explaining details of how to create our own scaffolding templates
    best regards
    Rodrigo

  25. nick4eva

    When I was installing Mvc Scaffolding I’ve got following error:

    PM> install-package mvcscaffolding
    ‘T4Scaffolding (≥ 0.8.5)’ not installed. Attempting to retrieve dependency from source…
    Done
    ‘EFCodeFirst 0.8′ already installed
    Successfully installed ‘T4Scaffolding 0.8.5′
    Successfully installed ‘MvcScaffolding 0.8.7′
    Mvc3ApplicationEF already has a reference to ‘EFCodeFirst 0.8′
    Successfully added ‘T4Scaffolding 0.8.5′ to Mvc3ApplicationEF
    Install-Package : You cannot call a method on a null-valued expression.
    At line:1 char:16
    + install-package <<<< mvcscaffolding
    + CategoryInfo : NotSpecified: (:) [Install-Package], CmdletInvocationException
    + FullyQualifiedErrorId : NuGet.VisualStudio.Cmdlets.InstallPackageCmdlet

  26. Bob King

    Well, right out of the box I run into an issue. This is a brand new VS2010, MVC3 RTM, MvcScaffolding install. The only difference from the instructions is my project name.

    When I run the ‘Scaffold Controller Team’ command, I get the following:

    Get-ProjectType : Cannot find a type matching the name ‘Team’. Try specifying the fully-qualified type name, including namespace.
    At C:\Documents and Settings\xxxxx\my documents\visual studio 2010\Projects\CardTracker\packages\MvcScaffolding.0.8.7\tools\Controller\MvcScaffolding
    .Controller.ps1:20 char:34
    + $foundModelType = Get-ProjectType <<<< $ModelType -Project $Project
    + CategoryInfo : NotSpecified: (:) [Get-ProjectType], InvalidOperationException
    + FullyQualifiedErrorId : T4Scaffolding.Cmdlets.GetProjectTypeCmdlet

  27. Bob King

    OK, I figured it out, but it required the uninstall/reinstall to work. I had not noticed that the project was created as a VB project, but I cut and pasted the code into Team.cs; starting over with a C# project, then uninstalling and reinstalling fixed it.

  28. Jimmy

    I m getting this error during installation….

    Successfully installed ‘EFCodeFirst 0.8′
    Successfully installed ‘T4Scaffolding 0.8.5′
    Successfully installed ‘MvcScaffolding 0.8.7′
    Successfully added ‘EFCodeFirst 0.8′ to XXX
    Successfully added ‘T4Scaffolding 0.8.5′ to XXX
    Successfully added ‘MvcScaffolding 0.8.7′ to XXX
    Install-Package : Exception calling “EnumerateFiles” with “3″ argument(s): “The path is not of a legal form.”
    At line:1 char:16
    + Install-Package <<<< MvcScaffolding
    + CategoryInfo : NotSpecified: (:) [Install-Package], CmdletInvocationException
    + FullyQualifiedErrorId : NuGet.VisualStudio.Cmdlets.InstallPackageCmdlet

  29. Larry Robson

    Woow… Very interesting post. And you can see this too, http://windows2008hosting.asphostportal.com/post/ASPNET-MVC-3-Hosting-ASPHostPortal-Credit-Card-Validator-Attribute-for-ASPNET-MVC-3.aspx, and for me it’s quite interesting too. I’ll wait another post from you.

  30. @Chris McKenzie I fixed the primary key problem by creating a field named simply “Id”. I think it has to do with creating more than one field of type int. Haven’t found much more info yet.

  31. David

    I was going crazy trying to get this to work, but always got:
    Get-PrimaryKey : Unspecified error (Exception from HRESULT: 0×80004005 (E_FAIL))
    At C:\dev\dotNet\MvcApplication2\packages\MvcScaffolding.0.9.1\tools\Controller\MvcScaffolding.Controller.ps1:25 char:29
    + $primaryKey = Get-PrimaryKey <<<< $foundModelType.FullName -Project $Project -ErrorIfNotFound
    + CategoryInfo : NotSpecified: (:) [Get-PrimaryKey], COMException
    + FullyQualifiedErrorId : T4Scaffolding.Cmdlets.GetPrimaryKeyCmdlet

    Finally I d/led the scaffolding source; once I saw what it was doing (and that it should work) I removed [Required] from the model and everything finally worked. The Primary Key field must be named “ID” or “[classname]ID” — case-insensitive.
    I hope there is/will be an attribute for flagging PK fields.

  32. TDeloford

    I have a standard EF4 context and have generated my POCO’s using the Entity Object Generator.

    I run the scaffolder generating the CRUD views and controller class, but the pages are broken, I see:

    System.InvalidOperationException: The type ‘MyPOCO’ is not a supported entity type

    [InvalidOperationException: The type MyPOCO' is not a supported entity type.]
    System.Data.Entity.Internal.DbSetDiscoveryService.GetSets() +860

    What am I doing wrong?

  33. Terrence

    Ideally for the Get-PrimaryKey error, we would be able to mark our key using [System.ComponentModel.DataAnnotations.Key]

  34. Terrence

    Ha. If you have {get; set;} after each property it works.

  35. Pingback: FreeSNAP, Day 2: And then there was CodePlex | The Fae Magic of Programming

  36. trace-projects

    am trying to get this to work using Visual Web Developer 2010 Express. so far am successful in installing it, but I can’t see the commands thru power shell, am I missing something?

  37. Gregor Suttie

    This is friggin awesome! – great work as usual Steve. Any plans for a new or updated book ?

  38. Shan

    The most recent update (9.2) is fantastic.

    I noticed that the scaffolding makes foreign keys required even though I do no specify the Required Data Annotation. Is there a way to specify that a foreign key relationship is NOT required, and can be null? I can override the validation, but the DB is still generated with that column not null.

  39. Pingback: ASP.NET MVC 3, IIS Express, SQLCE 4,Web Farm Framework, Orchard, WebMatrix发布

  40. Worked great on one table. I am all messed up adding 3 tables:
    Genere(title),Author(FirstName,LastName,Email) and
    Item(GenereId,AuthorId,Subject,Jist,URL)with PK’s & FK’s
    I would like to see an example to CRUD three similar tables.
    In the future samples I would like to see an example
    like the above tables which would retrieve some simple List’s of data via Interface and repository. Thanks

  41. Chris Peterson

    I’m unable to get this to compile as is.

    “The type or namespace name ‘Required’ could not be found.”

    If I remove required then all is well.

    Is there more documentation on this anywhere? How do we create relationships between models? How do we create default values for the models?

  42. Joe Mills

    Looks cool. Does it work in scenarios where your model is in a separate project?

  43. Pingback: Anunciando o lançamento da ASP.NET MVC 3, IIS Express, SQL CE 4, Web Farm Framework, Orchard e WebMatrix - ScottGu's Blog em Português

  44. Patric

    Chris Peterson: You need to import “System.ComponentModel.DataAnnotations”

  45. Shan

    Are there any issues as a result of creating a new database context for each model repository?

  46. kevin

    Hi,
    Like TDeloford above i take an System.InvalidOperationException: The type ‘ScaffoldTest.Models.Team’ is not a supported entity type.

    What are we doing wrong?

  47. scsfdev

    Hi,
    Can anybody guide me how can i install this MvcScaffolding if i’m behind a proxy. I got this error
    “The remote server returned an error: (407) Proxy Authentication Required.”
    I tried Google, Bing. No luck.
    Thanks.

  48. Nandu

    I ran the command “Scaffold Controller Team” as per the instructions and the required files were created. However, when i build the site, I get the error reading “‘SoccerSite.Models.SoccerSiteContext’ does not contain a definition for ‘Teams’ and no extension method ‘Teams’ accepting a first argument of type ‘SoccerSite.Models.SoccerSiteContext’ could be found (are you missing a using directive or an assembly reference?) ”

    The SoccerSiteContext has a constructor and no code in that. Should this file have any custom code to be added?

    (I just installed asp.net mvc3 and MvcScaffolding

  49. Camiel

    After seeing some demo’s at Webcamps in the Netherlands I’m experimenting with scaffolding too, but no luck, I’m affraid. One one machine (clean install win7, sql 2008 and win2010) I keep getting a “Not Implemented Exception” on Get-PrimaryKey. All I do is open a new MVC3 project, generate an edmx from database (1 table, 2 fields. PK is named ID).

    When I do the same trick on another box, the Scaffolding goes just right, but when running the project it throws the following exception: “The type ‘MvcApplication3.Models.Category’ is not a supported entity type.”.

    Any ideas?

  50. ShayKwait

    I get the same result as #49 Nandu is seeing. “TeamController.cs” is not created but “TeamsController.cs” with an “s” is.

  51. Robert

    Cannot install MvcScaffolding. See below:

    PM> Install-Package MvcScaffolding
    Install-Package : The current environment doesn’t have a solution open.
    At line:1 char:16
    + Install-Package <<<< MvcScaffolding
    + CategoryInfo : NotSpecified: (:) [Install-Package], Exception
    + FullyQualifiedErrorId : NuGet.VisualStudio.Cmdlets.InstallPackageCmdlet

    Interesting, tried as User and Administrator with the same results.

    Any ideas?

  52. Robert

    Never mind my bad.

  53. ShayKwait

    Follow up to #51: I destroyed the solution and started from scratch, adding SQL CE prior to issuing “Scaffold Controller Team”. This time it generated the following in the *Context.cs-
    public DbSet Teams { get; set; }
    It compiles fine now…

  54. Pingback: Releases de ASP.NET MVC 3, IIS Express, SQL CE 4, Web Farm Framework, Orchard, WebMatrix « Thinking in .NET

  55. To solve the error “The type or namespace name ‘Required’ could not be found.”, one must reference this namespace:

    (In C#:)
    using System.ComponentModel.DataAnnotations;

  56. Huw Leonard

    It appears that the scaffolding assumes an ID field of type int, and without one, it creates non-compilable code. Is there no way to use something else, such as a Guid? Or do we have to edit the generated code for every model object we want to add?

  57. Steve,

    I tried out the MVC scaffolding, and I have to say, I am rather impressed! You have no idea how many times I have to re-create the CRUD operation for each project that I work on.

    I was digging into the code, and nope, I can’t say I am that familiar with EntityFramework yet (I worked with nHibernate before). Now, it doesn’t really matter which ORM it is, my question has to do with how the DBSet object was initialized in the Context class.

    The class looks so simple, and yet, I have no idea how to modify it. For example, where does it take in a connection string, so that I can redirect that to a SQL Server 2008 R2, instead of SQLExpress? If someone can provide some documentations, that will be awesome. Thanks!

  58. Christian Monteiro

    I have the same Antony’s problem!

  59. Gregor Suttie

    Great work – this really is awesome, be nice to have a seperate Repository folder with Team Repository,cs in there but I’m sure that could be customised.

    Really love MVC, Nuget and the scaffolding – fantastic stuff!

  60. Pingback: Virtual conference MVCConf 2011 « vdcruijsen.net

  61. andyg8180

    any chance of getting the VB version of scaffolding updated? The C# works just fine but the VB vesion keeps breaking.

    this is the error im recieving

    Get-PrimaryKey : Not implemented (Exception from HRESULT: 0×80004001 (E_NOTIMPL))
    At C:\Test\Test\packages\MvcScaffolding.0.9.5\tools\Controller\MvcScaffolding.Controller.ps1:60 char:29
    + $primaryKey = Get-PrimaryKey <<<< $foundModelType.FullName -Project $Project -ErrorIfNotFound
    + CategoryInfo : NotSpecified: (:) [Get-PrimaryKey], NotImplementedException
    + FullyQualifiedErrorId : T4Scaffolding.Cmdlets.GetPrimaryKeyCmdlet

  62. Why did they get so specific with the method named GetAllTeams(), rather than simply GetAll(). With GetAll(), the method name would be the same across all interfaces of Teams, Users, Cars, etc.

    public interface ITeamRepository
    {
    void Add(Team post);
    void Delete(int id);
    IEnumerable GetAllTeams();
    Team GetById(int id);
    void Save();
    }

    After all, the other methods are not named AddTeam(), or DeleteTeam(), or SaveTeam(), or GetTeamById(), so why did they choose GetAllTeams().

    Here’s my vote to drop the noun from the GetAll() method.

  63. andyg8180

    I stated above that the VB doesnt work. I retested it. It works perfectly with Code First. I then tested it from creating an edmx with EF4 doing the model first approach. That is when the error is thrown…

    I retested the Model First scenario with C# and it works as advertied. My test was on a DB with a single table on it.

    Any info on the VB version of Scaffolding would be great.

    andyg8180

  64. Chris

    @Athony and @Christian – I think the DBContext connection string hookup is an example of the “convention over code” principle. If you look in the web.config, you’ll see a connection string entry with the same name attribute as the name of the DBContext. So, if you wanted to change the data store, you could replace the existing SQL Express connection string with a SQL Server 2008 R2 connection string.

  65. Need to upgrade an Intranet site and want to code it in MVC 3 in order to learn how to code in it. Plenty of explanations for SQL express databases but I have an existing SQL Server database that I need to pull data from. How do I access data from it? I receive the errorSystem.Data.Edm.EdmEntityType: : EntityType ‘…..’ has no key defined. Define the key for this EntityType.

  66. JonnyBoats

    Just tested this example and found one quirk. Scaffolding made Team plural so that the Url became http://…/teams instead of http://…/team.

    Also I loved your presentation at mvcConf, will you be making the code for supporting jqgrid available?

    Thank you.

  67. Raja

    For # 33 and # 47 System.InvalidOperationException: The type ‘ScaffoldTest.Models.Team’ is not a supported entity type. Please generate your model classes using Linq to SQL instead of EF.

  68. At first I couldn’t get the package to install correctly, it gave me some error loading a dll. If I retried it appeared successful. However then I received the same “The term ‘Scaffold’ is not recognized…” So I uninstalled and reinstalled to no avail. Finally, I ran VS as administrator, and viola, it works. And WOW I’m completely impressed! Nice work! :)

  69. Pingback: @stevesanderson: MvcScaffolding « Random misspellings

  70. Su

    Great Work!! I love MVC Scafolding. Pretty Amazing!!

  71. Reed

    How about the ability to do paging on the IEnumerable GetAll*() method?

  72. Paul Litwin

    Steve: When is MVCScaffolding going to be updated to work with the EF3.1 RC?

  73. Anthony

    Can I use this from outside of Visual Studio just using nuget.exe command-line and powershell? If so does there have to be a visual studio project or can I just pass a path to the Model directory? I ask since I would like use it outside of VS.

  74. If I have a bunch of fields (string type) that are not required and I don’t want them to be scaffolded in my views, how can I do that?

  75. Also, I’ve noticed (because I can be a little quick on the trigger sometimes) that scaffolding will actually scaffold a project that does not build. Hmmm.

  76. Pingback: Scaffolding Actions and Unit Tests with MvcScaffolding « Steve Sanderson’s blog

  77. Joe

    Have you folks tried this with MVC apps that are targeted at Azure? I can’t seem to get it to work. The Cmdlet seems to be unhappy about the number of parameters:

    PM> Scaffold Controller Test
    Invoke-Scaffolder : A positional parameter cannot be found that accepts argument ‘Test’.
    At line:1 char:9
    + Scaffold <<<< Controller Test
    + CategoryInfo : InvalidArgument: (:) [Invoke-Scaffolder], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,T4Scaffolding.Cmdlets.InvokeScaffolderCmdlet

  78. Alex

    The only other thing I would mention is to let people know to alter the ‘Context’ file if they want to name the database anything other than the generated default. Just tack on : base(“DatabaseName”) to the Context constructor with whatever database name you want.

  79. Michael

    I follwed you steps exactly and get th following error returned. Any Ideas?
    PM> Install-Package MvcScaffolding
    Install-Package : Too many automatic redirections were attempted.
    At line:1 char:16
    + Install-Package <<<< MvcScaffolding
    + CategoryInfo : NotSpecified: (:) [Install-Package], WebException
    + FullyQualifiedErrorId : NuGet.VisualStudio.Cmdlets.InstallPackageCmdlet

  80. Steve

    Michael, that looks like either a temporary issue with NuGet itself (not MvcScaffolding), or some kind of problem with your network (are you using a web proxy?). You may just want to try again later.

  81. Ron

    I have a viewmodel that consists of 2 lists of types required for a view, Stations and blends..When execute Scaffold StationTax, I receive the message “cannot find a model type to a controller”. I tried using the parameter -ModelType specifying my viewmodel; however, I receive the message, “cannot find primary key for type StationTaxesViewModel”, which is my viewmodel.

  82. Pingback: MvcScaffolding: Overriding the T4 Templates « Steve Sanderson’s blog

  83. Pingback: Pluralcast 39 : T4 with Gareth Jones - Pluralcast - Pluralsight

  84. Pingback: Elegant Code » Pluralcast 39 : T4 with Gareth Jones

  85. Nahuel Chaves

    Help! when i try to install it with “Install-Package MvcScaffolding” the following error occurs:

    Install-Package : No se encuentra el tipo [T4Scaffolding.NuGetServices.Services.ScaffoldingPackagePathResolver]: asegúrese de
    que está cargado el ensamblado que contiene este tipo.
    En línea: 1 Carácter: 16
    + Install-Package <<<< MvcScaffolding -Project AplicacionMVC
    + CategoryInfo : NotSpecified: (:) [Install-Package], RuntimeException
    + FullyQualifiedErrorId : NuGet.VisualStudio.Cmdlets.InstallPackageCmdlet

    I’ve tried to instal T4Scaffolding separately but no luck. I cant run the Scaffold command :(

  86. ARIF

    I got an error message when I write “Scaffold Controller Team”

    The term ‘Scaffold’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that t
    he path is correct and try again.
    At line:1 char:9
    + Scaffold <<<< Controller Team
    + CategoryInfo : ObjectNotFound: (Scaffold:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

    Note: My project successfully added EFCodeFirst 1.0, EntityFramework 4.1.10311.0, T4Scaffolding 0.9.9 and MvcScaffolding 0.9.9

  87. Excellent, Awesome article. Well-ordered and useful. Thanks Steve.

  88. buaziz

    am using EF4.1 Model First with MVC3, generated a DbContext model and tried to scaffold a couple of entities that have complex types.

    the _CreateOrEdit.vbhtml is not showing any of the complex types, and the Details.vbhtml is showing first property of the complex type.

    any advise.

  89. thanks for the proxies! i’ve been trying to find a proxy list for a while to unblock facebook youtube from my school

  90. Harjinder Kamboj

    My Models are:
    public class Designation
    {
    public int DesignationId { get; set; }
    [Required]
    public string Name { get; set; }
    public int SalaryLevel { get; set; }
    }

    public class Employee
    {
    public int EmployeeId { get; set; }
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }

    public Designation Designation { get; set; }

    }

    Now, I scaffold controllers for both Designation & Employee (first Designation, then Employee), I create some designations.

    Why don’t I get drop-down of Designations in UI of Employee/Create?

  91. Sam

    HI Steve,

    I have tested Scaffold tool in exist database.
    I could connect the database well even in the testing MVC web.

    But I don’t know how to apply the model class update into the database.
    I have tried to run the command with -Force option:
    PM>Scaffold Controller team –Repository -Force
    Nothing changed in DB.

    Is there any commands in PM or same way?

    Thanks
    Sam

  92. Dom

    I also end up with no styling visible on the pages, can anyone advise on how to rectify this?

    Many thanks

  93. @94 Dom, I had the same problem, it appears as though the scaffolder is not finding the master page.

    Include an explicit reference to the master page in your scaffold call:

    Scaffold Controller Team -Layout “/Views/Shared/Site.Master”

  94. Hi Steven!

    Just had an hour of fun: if you switch to SQL CE 4 (SQL Server Compact 4), update your tutorial to update the Web.Config ConnectionString, otherwise it will continue to go to the SQL Express instance.

    The name was the tricky part, you need the fully qualified name (found in Models\Project1MvcContext.vb).

  95. Hey Steven,
    Thanks so much for an awesome scaffolding framework with ready-to-use scaffolding (CRUD). It would be awesome to have you include localization support in the CRUD scaffolding, including the creation of a ‘starter’ resource file with english only resources.
    Thanks again and cheers from Toronto!

  96. Simon

    I tried everything as it says in the page but I get following exception: Invoke-Scaffolder : Cannot find a model type corresponding to a controller called ‘Team’. Try supplying a -ModelType parameter value.

    I am using VS2010 SP1 + ASP.NET MVC3 and ASP.NET Tools Update.

    Does anyone faced out the same issue?

    thanks
    simon

  97. Pingback: EF Code First e Geração Automática de Código (Data Scaffolding) com a Atualização das Ferramentas da ASP.NET MVC 3 - ScottGu's Blog em Português

  98. @Jimmy:

    The install script sometimes fails to detect what view engine your project is using.

    Try pasting the following into the package manager console:-

    “Set-DefaultScaffolder -Name View -Scaffolder MvcScaffolding.AspxView -SolutionWide” (or whatever the equivalent is for Razor if you’re using that)

    That should fix it. Haven’t yet figured out the conditions under which the install script fails.

  99. I have the same as #49 and #51

    Error 14 ‘xxx.Models.xxxContext’ does not contain a definition for ‘Team’ and no extension method ‘Team’ accepting a first argument of type ‘xxx.Models.xxxContext’ could be found (are you missing a using directive or an assembly reference?) …..\Controllers\TeamController.cs

    I just installed the mvc3 update and have 2010 sp1 and these packages:

  100. Pingback: ASP.NET , PHP , WEB DESIGN | Размисли

  101. Pingback: MVC3.1 Scaffolding Magic with Database (or Model) First , Not Just Code First - Aklıma Takılanlar | Zeytin.Net

  102. Pingback: ASP.NET MVC–Cascading Dropdown Lists Tutorial - Radu Enucă's Blog

  103. Pingback: EF Code First and Data Scaffolding with the ASP.NET MVC 3 Tools Update - Genel | Zeytin.Net

  104. Pingback: Mark Nichols » Blog Archive » Solus: Technology to Help with Peace of Mind on DeveloperSmackdown #49

  105. arckal

    I am not sure if someone could help me with this, I am not able to install the Package via Package Manager Console. I see following error:
    Install-Package : The package source named ‘NuGet official package source [https://go.microsoft.com/fwlink/?LinkID=206669]‘ is either invalid or not available and thus is c
    urrently unreachable.
    At line:1 char:16
    + Install-Package <<<< MvcScaffolding
    + CategoryInfo : NotSpecified: (:) [Install-Package], InvalidOperationException
    + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand

  106. Eircal

    Very nice!

  107. Kapil

    Just one correction with latest Mvc-Scaffolding and mvc3 installation …
    You need to have the following annotation as well in your model before generating the controller -
    [Key]public someProperty {get;set;}

    Where, Key is also defined via -
    using System.ComponentModel.DataAnnotations;
    Please add it to your tutorial.

  108. Igor

    Hi Steve. I’m trying to build Dependency Injection version.
    // If you are using Dependency Injection, you can delete the following constructor
    public CategoryController():this(new CategoryRepository()), but when I do it
    and leave:
    public CategoryController(ICategoryRepository categoryRepository), I get System.MissingMethodException.
    Certainly, new constructor has parameter unlike the first.
    What gently to do?
    What correct way of passing to use Ninject and Mock.
    Thanks.

  109. Tony

    Dear Steve,
    Thanks for all your support and posting of such usefull tutorials. However I encountered a problem that after hours can not still solve. If possible, please help: I did the Team class, es explained, all packages properly installed, I can see the scaffoleded classes made, but the Team when put after the http://localhost:58526/team, the does not work (recourse can not be found). I also can only see the DB in APP folder from the memberships and roles tables, but not the Team table. So no views or Db table views. What to do? I am perplexed. It seemed such a great help this Scaffolding thing- but now… Pleease help!

  110. marisk

    Anyone got a handle on this ?
    VS2010 sp1; MVC3 3.0.20105.0; MVC3 Visual Studio 2010 Tools update 3.0.20406.0

    PM> Install-Package MvcScaffolding
    ‘T4Scaffolding (≥ 1.0.2)’ not installed. Attempting to retrieve dependency from source…
    Done.
    Successfully installed ‘T4Scaffolding 1.0.2′.
    Install-Package : T4Scaffolding requires NuGet (Package Manager Console) 1.4 or later
    At line:1 char:16
    + Install-Package <<<< MvcScaffolding
    + CategoryInfo : NotSpecified: (:) [Install-Package], RuntimeException
    + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand

  111. Omri

    Did anyone figure out the styling issue? I also can’t get the Site.Master to be properly referenced by the scaffolded aspx views.

    Also, I couldn’t get the -Template / -MasterPage parameter to work…

    PM> Scaffold Controller Tasks -MasterPage=/Views/Shared/Site.Master
    Invoke-Scaffolder : A parameter cannot be found that matches parameter name ‘MasterPage=/Views/Shared/Site’.
    At line:1 char:57
    + Scaffold Controller Tasks -MasterPage=/Views/Shared/Site <<<< .Master
    + CategoryInfo : InvalidArgument: (:) [Invoke-Scaffolder], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,T4Scaffolding.Cmdlets.InvokeScaffolderCmdlet

  112. Dale

    @marisk
    go to Tools-Extension Manager and update the NuGet Package Manager

  113. marisk

    @Dale :

    Tnx. Works now.

  114. Steve

    Richard, Dom, Omri: Sorry for the delay in responding. It sounds like you’re using the ASPX view engine, which unlike Razor doesn’t have a notion of a default master page. So, you need to specify your master page explicitly like Steve Morgan described, e.g.:

    Scaffold Controller Person -MasterPage ~/Views/Shared/Site.Master

  115. Pingback: MvcScaffolding: Standard Usage - Steve Sanderson’s blog - As seen on YouTube™

  116. Does this handle composite primary keys? I have a model similar to the one in this question. http://stackoverflow.com/questions/3711938/ado-net-entity-framework-composite-primary-key-crud
    Scaffolding works, but at runtime DBContext is throwing an exception complaining about the relationship table not have a primary key.

  117. Getting errors when trying to scaffold a controller based on a model in this case called ‘culture’…

    Add-ProjectItemViaTemplate : E:\Websites\TyscaMVC\packages\MvcScaffolding.1.0.2\tools\RazorView\_CreateOrEdit.vb.t4(143,0) : error BC30035: Compiling transformation: Syntax error.
    At E:\Websites\TyscaMVC\packages\MvcScaffolding.1.0.2\tools\RazorView\MvcScaffolding.RazorView.ps1:49 char:27
    + Add-ProjectItemViaTemplate <<<< $outputPath -Template $Template -Model @{
    + CategoryInfo : NotSpecified: (:) [Add-ProjectItemViaTemplate], Exception
    + FullyQualifiedErrorId : T4Scaffolding.Cmdlets.AddProjectItemViaTemplateCmdlet

  118. I just tried running scaffolding, using the latest version, and it generated aspx-style views… how do i force it to use razor ones?

  119. ok figured it out… weird that it didnt detect my project was already using razor.

  120. Bill

    On my version, EntityFramework 4.1.10715.0′, System.Data.Entity.Database is a namespace and not a class. DbDatabase IS a class in that namespace and it contains the SeInitializer method.

    I had to use the following to get the demo to remake my database.

    System.Data.Entity.Database.DbDatabase.SetInitializer(new System.Data.Entity.Database.DropCreateDatabaseIfModelChanges ());

  121. Bill

    see post above – comment box doesnt like the arrow keys and removed them and the following from inside DropCreate…Changes.

    Mvc3ScaffoldDemo.Models.Mvc3ScaffoldDemoContext

  122. Rita

    Getting an error when I use the following command.
    PM> Scaffold Controller Team
    Invoke-Scaffolder : A positional parameter cannot be found that accepts argument ‘Team’.
    At line:1 char:9
    + Scaffold <<<< Controller Team
    + CategoryInfo : InvalidArgument: (:) [Invoke-Scaffolder], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,T4Scaffolding.Cmdlets.InvokeScaffolderCmdlet

    Could you help me to solve this problem please~~~~~~~?

  123. Rawad

    If anyone facing errors while executing the command this due to the version of package manager console it should be later than 1.4 update it then reinstall scaffolding
    http://visualstudiogallery.msdn.microsoft.com/27077b70-9dad-4c64-adcf-c7cf6bc9970c

  124. Ben

    I am getting the following error when opening my project:

    Set-DefaultScaffolder : Cannot use the default name ‘Views’ because this clashes with an actual scaffolder n
    ame
    At C:\Projects\WITTrainees\packages\MvcScaffolding.1.0.4\tools\init.ps1:36 char:22
    + Set-DefaultScaffolder <<<< -Name Views -Scaffolder MvcScaffolding.Views -SolutionWide -DoNotOverwriteExis
    tingSetting
    + CategoryInfo : NotSpecified: (:) [Set-DefaultScaffolder], InvalidOperationException
    + FullyQualifiedErrorId : T4Scaffolding.Cmdlets.SetDefaultScaffolderCmdlet

  125. Hamid Ouakil

    it looks like the scaffolder ignores [ScaffoldColumn(fasle)] it seams it would an overkill to have to use a custom template for this to work

  126. Hi,

    I have hosted my website but its not taking up the sql instance. I tried to run the app in local system with remote access to SQL server and the app searches for local SQLSERVER instance. Is this by default that MVC Scaffolded app searches for local instance?

    Note: I have made necessary changes in connection string.

    Please guide me as I am unable to host my web app.

  127. Wow, awesome blog format! How lengthy have you been running a blog for? you make running a blog look easy. The whole look of your website is excellent, let alone the content material!

  128. ryan

    Hi,

    How to validate jquery grid input?

  129. Hey dude! :) Gotta say love scaffold!!

    But one question i have a mdf attached in my web.config..

    My scaffold works just fine, but where the h does it add the data in the mdf file?! :D Can seem to find it.

  130. Mila

    am trying to get this to work Visual Web Developer 2010 EE and it shows me-Error list:Error 1 The type or namespace name ‘RequiredAttribute’ could not be found (are you missing a using directive or an assembly reference?) C:\Users\Mila\documents\visual studio 2010\Projects\SoccerSite\SoccerSite\Models\Class1.cs 11 10 SoccerSite

    Error 2 The type or namespace name ‘Required’ could not be found (are you missing a using directive or an assembly reference?) C:\Users\Mila\documents\visual studio 2010\Projects\SoccerSite\SoccerSite\Models\Class1.cs 11 10 SoccerSite

  131. MVC4 Coder

    This is really powerful! Any chance for an update to support the preview of MVC 4?

  132. Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

    Compiler Error Message: CS0246: The type or namespace name ‘GetUserDetails’ could not be found (are you missing a using directive or an assembly reference?)

    Source Error:

    Line 13: public partial class Login : System.Web.UI.Page
    Line 14: {
    Line 15: private GetUserDetails user = new GetUserDetails();
    Line 16:
    Line 17: protected void Page_Load(object sender, EventArgs e)

    Source File: c:\Documents and Settings\NgobeniR\My Documents\Visual Studio 2005\nasp\nasp[\nasp[\login.aspx.cs Line: 15

  133. Magnificent beat ! I wish to apprentice while you amend your web site, how can i subscribe for a blog site? The account aided me a applicable deal. I had been tiny bit familiar of this your broadcast provided vibrant clear idea

  134. So far this is great stuff – I get all the way through the installation and scaffolding and get a build success, but when I go to run my app I get an error:

    The type ‘…Team’ was not mapped. Check that the type has not been explicitly excluded by using the Ignore method or NotMappedAttribute data annotation.

    This occurs on the constructor of the context:
    MvcScaffoldTestContext context = new MvcScaffoldTextContext();

    I looked in the generated context and the DbSet property is there for the class, and as I said, the scaffolding went fine and all the Views/Controllers were generated as well.

    What might be causing this?

  135. How to validate jquery grid input?

  136. tom

    Just in case it helps someone else, you do need to update your package manager from th vs extension manager if you arent running nuget v 1.4 or above

  137. I’ve learn a few just right stuff here. Definitely worth bookmarking for revisiting. I surprise how so much attempt you place to make this sort of fantastic informative web site.

  138. this is driving me nuts – please take a look at this SO post i made. My scaffolded project is now blowing up on model properties that are nullable value types. Used to work fine. http://stackoverflow.com/questions/8313858/mvc3-createoredit-template-now-blowing-up-on-nullable-int-field/8314158#8314158

  139. Hi, Neat post. There’s an issue together with your web site in internet explorer, could test this? IE still is the marketplace chief and a huge section of people will miss your magnificent writing because of this problem.

  140. I’m really impressed together with your writing skills as neatly as with the format for your weblog. Is that this a paid subject matter or did you customize it your self? Either way keep up the excellent high quality writing, it?s uncommon to peer a great blog like this one these days..

  141. Julen

    I am unable to run the first step of the example.

    I install the package and write the Team class properly and I scaffold using the tool. The thing is that the context it creates lacks the “Team” member that uses in the controller, see example:

    public ViewResult Index()
    {
    return View(context.Team.ToList());
    }

    The context just has:

    public DbSet Teams { get; set; }

    Am I missing something?

    Thanks a lot!

  142. Tom McNamee

    Steve: Thanks for your great work. Even running as an admin, I can’t get Powershell to recognize ‘Scaffold’ and a command. I upgraded NuGet, restarted VS, uninstalled and reinstalled and updated MvcScaffolding. Ideas?

  143. Alex J

    I installed the SQL Server Compact like the article says, and it kind of blew everything out of the water. (It doesn’t like SQLCEEntityFramework.cs.) How do I fix this?

    2 Errors in SQLCEEntityFramework.cs:

    Error 1 A using namespace directive can only be applied to namespaces; ‘System.Data.Entity.Database’ is a type not a namespace

    Error 2 The name ‘DbDatabase’ does not exist in the current context

    Error 3 The type or namespace name ‘SqlCeConnectionFactory’ could not be found

    The problem areas of the .cs files are:

    using System.Data.Entity.Database;

    ~and~

    DbDatabase.DefaultConnectionFactory = new SqlCeConnectionFactory(“System.Data.SqlServerCe.4.0″);

  144. Steve

    The term ‘Scaffold’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path w
    as included, verify that the path is correct and try again.
    At line:1 char:9
    + Scaffold <<<< Controller Definition
    + CategoryInfo : ObjectNotFound: (Scaffold:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

    I reinstalled Nuget, recreated the mvc site, then ran: Install-Package MvcScaffolding

  145. Gilberto Carcano

    I’ve downloaded the source code of MvcScaffolding from CodePlex to play with. My goal is to obtain a particular kind of pluralization. Can you tell me how to install the new version after recompiled the entire solution? I’ve found this workaround: I copy the new T4Scaffolding.dll to the tools directory of my target project. Then I uninstalled and reinstalled the package from the Package Manager Console. The new dll will not be overwritten and so it will live in my project. I know this isn’t the best way… but I’m new to NuGet. However, this workaround is unuseful for to add new cmdlets as I need. Thank you so much.

  146. Jeff

    Pretty much what Steve said above. I was walking through this tutorial and sure I modified things along the way, but just things in the newly created class and here’s what I see:

    PM> Scaffold Controller User
    The term ‘Scaffold’ is not recognized as the name of a cmdlet, function, script file, or operable program. C
    heck the spelling of the name, or if a path was included, verify that the path is correct and try again.
    At line:1 char:9
    + Scaffold <<<< Controller User
    + CategoryInfo : ObjectNotFound: (Scaffold:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

    Yes my class name is User instead of Team.

    What do you think?

  147. Jeff

    I just noticed that Steve you are the person with the answers so forgive my statement above. In that regard I looked at you answer and said to myself, hmm maybe I need to recreate the project. I had just updated Nuget so I could use Scaffolding, but the project had already been created. I decided I could just create a new project and should put me in line with what you were saying above.

    When I created a new project tried to install Scaffolding I got a response that said it was installed and one that said I had to update Nuget. Am I missing something here or what?

    I am about to trash this whole MVC thing and just do databases the old fashioned way because at least I know how.

    Here is what I got:

    PM> Install-Package MvcScaffolding
    ‘T4Scaffolding’ not installed. Attempting to retrieve dependency from source…
    Done.
    Successfully installed ‘T4Scaffolding 1.0.5′.
    Install-Package : T4Scaffolding requires NuGet (Package Manager Console) 1.4 or later
    At line:1 char:16
    + Install-Package <<<< MvcScaffolding
    + CategoryInfo : NotSpecified: (:) [Install-Package], RuntimeException
    + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand

  148. mattiasw

    Interesting idea, but it would really be interesting to understand how it finds stuff. It only works in nice newly created single-projects solutions for me.

    In my ordinary solution, with the command “Scaffold Controller RequestLicenses” I get

    PM> Scaffold Controller RequestLicenses
    Invoke-Scaffolder : A positional parameter cannot be found that accepts argument ‘RequestLicenses’.
    At line:1 char:9
    + Scaffold <<< Scaffold Controller RequestLicenses
    Scaffolding RequestLicensesController…
    MvcScaffoldingPlayContext already has a member called ‘RequestLicenses’. Skipping…
    Added controller Controllers\RequestLicensesController.cs
    Added Create view at ‘Views\RequestLicenses\Create.cshtml’
    Added Edit view at ‘Views\RequestLicenses\Edit.cshtml’
    Added Delete view at ‘Views\RequestLicenses\Delete.cshtml’
    Added Details view at ‘Views\RequestLicenses\Details.cshtml’
    Added Index view at ‘Views\RequestLicenses\Index.cshtml’
    Added _CreateOrEdit view at ‘Views\RequestLicenses\_CreateOrEdit.cshtml’

  149. Hasan Çetinkaya

    PM> Scaffold Controller Post -Repository -Force
    Scaffolding PostController…
    MvcApplication5Context already has a member called ‘Posts’. Skipping…
    Invoke-ScaffoldTemplate : Failed to render template
    At line:1 char:23
    + param($c, $a) return . <<<< $c @a
    + CategoryInfo : NotSpecified: (:) [Invoke-ScaffoldTemplate], Exception
    + FullyQualifiedErrorId : T4Scaffolding.Cmdlets.InvokeScaffoldTemplateCmdlet

    Add-ProjectItemViaTemplate : error : Failed to load base class 'DynamicTransform' from which Transformation clas
    s inherits.
    At C:\a\MvcApplication5\packages\T4Scaffolding.1.0.5\tools\EFRepository\T4Scaffolding.EFRepository.ps1:47 char:2
    7
    + Add-ProjectItemViaTemplate <<<< $outputPath -Template Repository -Model @{
    + CategoryInfo : NotSpecified: (:) [Add-ProjectItemViaTemplate], Exception
    + FullyQualifiedErrorId : T4Scaffolding.Cmdlets.AddProjectItemViaTemplateCmdlet

    Invoke-ScaffoldTemplate : Failed to render template
    At line:1 char:23
    + param($c, $a) return . <<<< $c @a
    + CategoryInfo : NotSpecified: (:) [Invoke-ScaffoldTemplate], Exception
    + FullyQualifiedErrorId : T4Scaffolding.Cmdlets.InvokeScaffoldTemplateCmdlet

    Add-ProjectItemViaTemplate : error : Failed to load base class 'DynamicTransform' from which Transformation clas
    s inherits.
    At C:\a\MvcApplication5\packages\MvcScaffolding.1.0.6\tools\Controller\MvcScaffolding.Controller.ps1:101 char:27
    + Add-ProjectItemViaTemplate <<<< $outputPath -Template $templateName -Model @{
    + CategoryInfo : NotSpecified: (:) [Add-ProjectItemViaTemplate], Exception
    + FullyQualifiedErrorId : T4Scaffolding.Cmdlets.AddProjectItemViaTemplateCmdlet

    Added Create view at 'Views\Post\Create.cshtml'
    Added Edit view at 'Views\Post\Edit.cshtml'
    Added Delete view at 'Views\Post\Delete.cshtml'
    Added Details view at 'Views\Post\Details.cshtml'
    Added Index view at 'Views\Post\Index.cshtml'
    Added _CreateOrEdit view at 'Views\Post\_CreateOrEdit.cshtml'

  150. Shahin kiassat

    Small refactoring :
    Instead of : (In IQueryable AllIncluding)
    IQueryable query = context.Members;
    foreach (var includeProperty in includeProperties) {
    query = query.Include(includeProperty);
    }
    return query;
    Its better to write :
    return includeProperties.Aggregate<Expression<Func>, IQueryable>(context.Members, (current, includeProperty) => current.Include(includeProperty));

    Regards

  151. You know therefore significantly in the case of this subject, produced me individually consider it from so many various angles. Its like women and men don’t seem to be interested until it’s something to accomplish with Woman gaga! Your personal stuffs great. Always take care of it up!

  152. Hello there, I discovered your web site by the use of Google at the same time as searching for a comparable subject, your web site came up, it seems great. I’ve bookmarked to my favourites|added to my bookmarks.

  153. Paul-orado

    PM> Install-Package MvcScaffolding
    ‘T4Scaffolding’ not installed. Attempting to retrieve dependency from source…
    Done.
    ‘EntityFramework (≥ 4.1.10311.0)’ not installed. Attempting to retrieve dependency from source…
    Done.
    You are downloading EntityFramework from Microsoft, the license agreement to which is available at http://go.microsoft.com/fwlink/?LinkId=224682. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device.
    Successfully installed ‘EntityFramework 4.1.10715.0′.
    Successfully installed ‘T4Scaffolding 1.0.5′.
    Install-Package : T4Scaffolding requires NuGet (Package Manager Console) 1.4 or later
    At line:1 char:16
    + Install-Package <<<

    I read the posts on Aug 15 by marisk and Aug 17 by Dale. But when I try and update NuGet like Dale suggested I get an error:

    1/17/2012 7:22:25 PM – Microsoft Visual Studio Extension Installer
    1/17/2012 7:22:25 PM – ——————————————-
    1/17/2012 7:22:25 PM – Initializing Install…
    1/17/2012 7:22:25 PM – Extension Details…
    1/17/2012 7:22:25 PM – Identifier : NuPackToolsVsix.Microsoft.67e54e40-0ae3-42c5-a949-fddf5739e7a5
    1/17/2012 7:22:25 PM – Name : NuGet Package Manager
    1/17/2012 7:22:25 PM – Author : Microsoft Corporation
    1/17/2012 7:22:25 PM – Version : 1.6.21215.9133
    1/17/2012 7:22:25 PM – Description : A collection of tools to automate the process of downloading, installing, upgrading, configuring, and removing packages from a VS Project.
    1/17/2012 7:22:25 PM – Locale : en-US
    1/17/2012 7:22:25 PM – MoreInfoURL : http://docs.nuget.org/
    1/17/2012 7:22:25 PM – InstalledByMSI : False
    1/17/2012 7:22:25 PM – MinFramework : 4.0
    1/17/2012 7:22:25 PM – MaxFramework : 4.0
    1/17/2012 7:22:25 PM –
    1/17/2012 7:22:25 PM – Supported Visual Studio Editions :
    1/17/2012 7:22:25 PM – Version : 10.0
    1/17/2012 7:22:25 PM – Pro
    1/17/2012 7:22:25 PM – IntegratedShell
    1/17/2012 7:22:25 PM – VWDExpress
    1/17/2012 7:22:25 PM – VPDExpress
    1/17/2012 7:22:25 PM – Version : 11.0
    1/17/2012 7:22:25 PM – Pro
    1/17/2012 7:22:25 PM – IntegratedShell
    1/17/2012 7:22:25 PM – VWDExpress
    1/17/2012 7:22:25 PM – VPDExpress
    1/17/2012 7:22:25 PM –
    1/17/2012 7:22:25 PM – Supported Isolated Shells :
    1/17/2012 7:22:25 PM –
    1/17/2012 7:22:25 PM – References :
    1/17/2012 7:22:25 PM –
    1/17/2012 7:22:25 PM – The extension will be upgraded from version 1.2.20325.9034.
    1/17/2012 7:22:28 PM – The following target products have been selected…
    1/17/2012 7:22:28 PM – Microsoft Visual Studio 2010 Professional
    1/17/2012 7:22:28 PM –
    1/17/2012 7:22:28 PM – Verifying matching extension signatures before updating…
    Installed Extension Path: C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\Extensions\Microsoft Corporation\NuGet Package Manager\1.2.20325.9034\
    Update Extension Path: c:\users\ban57834\appdata\local\temp\tmp680d.tmp
    1/17/2012 7:22:28 PM – VSIXInstaller.SignatureMismatchException: The signature on the update version of ‘NuGet Package Manager’ does not match the signature on the installed version. Therefore, Extension Manager cannot install the update.
    at VSIXInstaller.Common.VerifyMatchingExtensionSignatures(IInstalledExtension installedExtension, IInstallableExtension updateExtension)
    at VSIXInstaller.InstallProgressPage.BeginInstallVSIX(SupportedVSSKU targetAppID)
    1/17/2012 7:22:28 PM – Install Error : VSIXInstaller.SignatureMismatchException: The signature on the update version of ‘NuGet Package Manager’ does not match the signature on the installed version. Therefore, Extension Manager cannot install the update.
    at VSIXInstaller.Common.VerifyMatchingExtensionSignatures(IInstalledExtension installedExtension, IInstallableExtension updateExtension)
    at VSIXInstaller.InstallProgressPage.BeginInstallVSIX(SupportedVSSKU targetAppID)

    Anybody see this? Any suggestions?

  154. giradhari

    Error 4 The type or namespace name ‘Logic’ does not exist in the namespace ‘WebChat’ (are you missing an assembly reference?).

    Error 5 The type or namespace name ‘ChatRoom’ could not be found (are you missing a using directive or an assembly reference?).

    sir plz answer my problems

  155. I’ve been exploring for a little for any high quality articles or weblog posts on this sort of house . Exploring in Yahoo I ultimately stumbled upon this site. Reading this information So i’m happy to convey that I’ve a very good uncanny feeling I found out just what I needed. I such a lot indubitably will make sure to don?t overlook this web site and give it a glance on a constant basis.

  156. Ian

    PM> Update-Package MvcScaffolding
    No updates available for ‘MvcScaffolding’.

    PM> Uninstall-Package MvcScaffolding -RemoveDependencies
    Successfully removed ‘MvcScaffolding 1.0.6′ from OA.
    Successfully removed ‘T4Scaffolding 1.0.5′ from OA.
    Successfully removed ‘EntityFramework 4.1.10331.0′ from OA.
    Successfully uninstalled ‘MvcScaffolding 1.0.6′.
    Successfully uninstalled ‘T4Scaffolding 1.0.5′.

    PM> Install-Package MvcScaffolding
    ‘T4Scaffolding’ not installed. Attempting to retrieve dependency from source…
    Done.
    Successfully installed ‘T4Scaffolding 1.0.5′.
    Install-Package : T4Scaffolding requires NuGet (Package Manager Console) 1.4 or
    later
    At line:1 char:16
    + Install-Package <<< Install-Package MvcScaffolding
    Successfully installed ‘MvcScaffolding 1.0.6′.
    Successfully added ‘EntityFramework 4.1.10331.0′ to OA.
    Successfully added ‘T4Scaffolding 1.0.5′ to OA.
    ‘InstallationDummyFile.txt’ already exists. Skipping…
    Successfully added ‘MvcScaffolding 1.0.6′ to OA.

    PM> Scaffold Controller Challenge -Repository
    The term ‘Scaffold’ is not recognized as the name of a cmdlet, function, script
    file, or operable program. Check the spelling of the name, or if a path was in
    cluded, verify that the path is correct and try again.
    At line:1 char:9
    + Scaffold <<<

  157. Ian

    Fixed issue by re-installing NuGet

  158. Sam

    One or more validation errors were detected during model generation:

    System.Data.Edm.EdmNamespace: Name: The specified name is not allowed: ‘SS.WS._5._0.Models’

    Scaffolding success, but the error is threw at run time.

    What could be the issue?

    Thanks,

    Sam

  159. Sam

    Problem solved!

  160. Simply want to say your article is as amazing. The clearness in your publish is simply excellent and that i could suppose you are an expert on this subject. Fine together with your permission let me to seize your feed to keep updated with impending post. Thanks one million and please carry on the gratifying work.

  161. Try
    Scaffold Mailer.Razor if you are using Razor View Engine

  162. Danny

    Relationships in classes fails :/

    public class Poll
    {
    public int ID { get; set; }
    [Required]
    public string Title { get; set; }
    [Required]
    public string Description { get; set; }
    [Required]
    public bool Status { get; set; }
    [Required]
    public string Username { get; set; }
    [Required]
    public List Questions { get; set; }
    }

    public class Question
    {
    public int ID { get; set; }
    [Required]
    public string Description { get; set; }
    [Required]
    public int Votes { get; set; }
    }

  163. Danny

    Btw the brackers between public List Questions { get; set; } fail to display in the comment box :/ thnks

  164. Magnus Karlsson

    http://geekswithblogs.net/MagnusKarlsson/archive/2012/02/29/entity-framework-4.1-code-first–use-mssqlserver-instead-of-express.aspx

    Here is an example to a connectionstring using a MSSQL server. I uninstalled the Express server to keep focus on “the real deal”.

  165. I don’t even know the way I finished up right here, but I thought this publish was good. I do not know who you are but certainly you are going to a famous blogger for those who are not already. Cheers!

  166. Noob

    Hi, is there a way to scaffold all the models? i used Scaffold ControllerWithEntityMetadata -Context myContext as for now but i still have 100++ model to go :(

  167. Mike

    I have installed MVC4 and it contained a template called: “Controller with read/write actions and views, using Entity Framework”. I’m not sure if I should be using that one or the one you describe. It produces different code and I’m trying to figure out if one is better than the other but being new to MVC I can’t tell which is the ‘newer’ code.

  168. Jason

    Its different Mike I am using MVC 4 Beta and have some experience with it, it uses the default Templates found at C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\CSharp\Web\MVC 4\CodeTemplates these are used by the controller wizard and view wizard to create controllers and views and you can alter these to generate your own view or controller code this is a step furhter where based on scaffolding (class attributes) it will produce more sophisticated code to create the data layer, Essentially create the Controller View then the EF code (db) to save and retrieve data

  169. Jason

    By the way great book Steve look forward to Pro ASP.NET MVC 4 coming out

  170. Hey Steven, good job bro and really gratz, awsome POST.

  171. Hello Steven, I am trying to run the Reverse Enginer Code First feature in vs2011 and then run the mvcScaffolding, however it seams to work but has a problem with pluralisation. Is it supported?

  172. srinivas T

    i am trying to work out on this example i was installed the mvcscaffolding.whenever i am trying to install Install-Package EFCodeFirst.SqlServerCompact through Package Manager Console its displaying error like
    “Install-Package : Unable to find package ‘EFCodeFirst.SqlServerCompact’.
    At line:1 char:16
    + Install-Package <<<< EFCodeFirst.SqlServerCompact
    + CategoryInfo : NotSpecified: (:) [Install-Package], InvalidOperationException
    + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand"
    what is wrong in it ?is i am doing any wrong in it?

  173. fang

    why can’t i scaffold like this ? Scaffold View User CreateSystemUser -Model System.Web.Security.MembershipUser -template Create

  174. Hi,

    This is Jones druman
    This blog was simply great post byb you. I really appreciate your blog. Really awesome blog I would like to

    know more about this. Please give some ideas about your blog. Thanks…………………………………….
    Live project Training

  175. Ed Van

    srinivas T –> For me this line worked

    Install-Package EFCodeFirst.SqlServerCompact -Version 0.8.8482.1
    ——————————————
    Great blog, thank you for sharing!

  176. Gleb

    Great tool, but please any advise why is it so slow? The scaffolding of simple model in empty project (as described in this tutorial) trakes about 15 seconds, which is slow still acceptable, but after we added some scaffolding logic, based on our custom metadata attributes, the scaffolding of a model with some one-to-many relationships takes 5 minutes and more, which makes it unusable. Any ways to improve the performance?

  177. Jed Lawrence

    Like many of the posted messages in your blog, I can install the MvcScaffolding package but regardless of how many times I uninstall and reinstall the package it NEVER recognizes the “Scaffold Controller Item”. I have tried this in 7 different Windows PCs all with the same problem, the Scaffold command is NOT recognized. The scafffolding and DRUD support really sound like a very nive set of features but it seems that the tools are very fragile.

  178. Sailaja

    Hi Steve,
    Its really very useful post for beginners. I tried to implement the same. but when i try to create controller i got the following error. please help me to get out of this error.

    PM> Scaffold Controller Team
    The term ‘Scaffold’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included,
    verify that the path is correct and try again.
    At line:1 char:9
    + Scaffold <<<< Controller Team
    + CategoryInfo : ObjectNotFound: (Scaffold:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

    Thanks.

  179. Allen

    The right is remove the Nuget and reinstall it. It will fix all issues.

    Also can run Install-Package EntityFramework.SqlServerCompact if you don’t have express database

  180. Ace

    Help! I am able to execute the scaffolding commands. But when i run the application, it says following errors

    ~/Views/continents/Index.aspx
    ~/Views/continents/Index.ascx
    ~/Views/Shared/Index.aspx
    ~/Views/Shared/Index.ascx

    FYI that i only have cshtml files inside the continents folder, no aspx pages created!

    my shared folder is also empty..i understand that the controller is looking for .aspx page, but the scaffold command doesnt create aspx pages..

    Pls help what change is to be done to make the app running.

    Thanks
    Ace

  181. Ace

    sorry , i missed the error ..

    The view ‘Index’ or its master was not found. The following locations were searched:

    ~/Views/continents/Index.aspx
    ~/Views/continents/Index.ascx
    ~/Views/Shared/Index.aspx
    ~/Views/Shared/Index.ascx

    FYI that i only have cshtml files inside the continents folder, no aspx pages created!

    my shared folder is also empty..i understand that the controller is looking for .aspx page, but the scaffold command doesnt create aspx pages..

    Pls help what change is to be done to make the app running.

    Thanks
    Ace