Tormod Haugene
Tormod Haugene

Reputation: 3696

Scaffolding Controller in MVC 4, Solution to error: "Error: Unable to retrieve metadata for 'Model'. The argument 'connectionstring' cannot be null

When trying to create a controller in MVC 4 with Scaffolding (EF and CRUD), I got the following error:

"Unable to retrieve metadata for MyModel. The argument 'connectionString' cannot be null, empty or contain only white space."

I spent quite some time trying to figure this out, without any success from all posts I found online. I did however find a way to solve it, and though I would share it here.

My Solution:

  1. Comment out your entire current Context class for your model - if you have any.
  2. Remove any other connection strings for the object you are targeting, if you tried to solve the problem by Adding a connection string, like I did...
  3. Now add the Controller using the Add dialog: Right click the "Controllers"-folder, and navigate to "Add->Controller...", give the a controller name, and select the Model class to use. In the Data Context Class, choose "New Data Context..". The last part is important, as the scaffolder now will create a fully functional connection string and context class for you!
  4. If you already had a lot of work down in your previous Context class, use the new one as a template, and copy paste your old one into the one just created.
  5. Then delete the controller and views created, and add another controller using the add-dialog as in step 3, but this time with the Data Context Class as generated for you previously.
  6. There might be some bugs regarding automatic naming conventions, but these should be rather straight forward to fix.

For the reference, I am working in Visual-Studio 2012.

This is the way it worked for me. Hopefully it will help any others who are stuck on the same issue. All feedback or better solutions are appreciated

Upvotes: 2

Views: 1827

Answers (1)

Elder Santos
Elder Santos

Reputation: 319

In my Case I just remove the line below from my Context class

Database.SetInitializer(new MigrateDatabaseToLatestVersion<ContextClass, Configuration>());

After that, build and right-click con Controller folder to add a new controller. Done

Upvotes: 2

Related Questions