65

PROBLEM:

I have updated to Visual Studio 2013 update 2 and now I cannot scaffold controllers.

The problem is not project specific: when I try to scaffold a controller, I get the following error in ALL and ANY project:

There was an error running the selected code generator:
'Exception has been thrown by the target of an invocation.'

It was working before updating to Visual Studio 2013 update 2.

Have googled the issue to death, but none of the various suggestions work

Eg:

  1. Commenting out OnModelCreating in my context;

  2. Removing packages such as MvcScaffolding, etc (I have none installed and it doesn't work with ANY project);

I have modified/customised some of the templates, but it was working after the changes.

EDIT:

I uninstalled Visual Studio 2013 Update 2 and thereby reverted to Visual Studio version 12.0.21005.1 REL.

The problem has disappeared. Therefore, the problem is quite definitely with Update 2.

QUESTION:

Does anyone (including Microsoft) know of a fix?

EDIT 2:

Farruk Subhani's answer does not address the question: The question clearly states that removing references to MVCScaffolding does not solve the issue.

I have added a 200 point bounty, please address the question as clearly stated.

awrigley
  • 13,481
  • 10
  • 83
  • 129
  • Yes, and scaffolding the context option for the controller and views. – awrigley Jun 29 '14 at 21:53
  • check if your EF assemblied are up to date with downloads – Dave Alperovich Jun 30 '14 at 02:43
  • There is no problem with EF or its assemblies. I have EF 6.1 installed. If there was a problem, scaffolding wouldn't work (as it does) if VS 2013 Update 2 is not installed (ie, just VS 2013 original flavour). – awrigley Jun 30 '14 at 15:19
  • Are you using Code First? – Justin Jul 03 '14 at 19:49
  • Yes, and it all works when I revert to Visual Studio 2013 (ie, by uninstalling update 2). – awrigley Jul 03 '14 at 20:20
  • 1
    I solve this problem updating Visual Studio 2013 to Update 3. – mejiamanuel57 Sep 04 '14 at 20:22
  • 1
    I'm having the same problem with VS2015 Update 2 running against the latest .net 5 (.net core 1.0). I've done nothing non-standard but have simply been following this https://docs.asp.net/en/latest/tutorials/your-first-aspnet-application.html. Haven't found a solution yet... – LDJ Apr 07 '16 at 08:30

16 Answers16

35

Hey for all of you that nothing works, the real answer is you need to remove ANYTHING that has a configSource on the web.config and the connection string needs to be inlined.

EDIT:

Someone pointed out that it needs to be only <configSettings>, <appSettings>, and <connectionStrings> tags NOT using a configSource attribute. And that he was still able to use configSource attributes elsewhere, such as the rewriter tag.

I think it's that the tooling cannot follow configSource locations for the stuff it uses like connection strings and application settings.

Microsoft should be on this issue if not fixed yet.

EDIT 2:

Even thought @awrigley has marked his answer as correct it's a known Visual Studio bug. I've managed to tell then and I think it will get some attention soon. https://github.com/aspnet/Tooling/issues/169#issuecomment-144197015

regisbsb
  • 3,664
  • 2
  • 35
  • 41
12

A combination of things have worked for me:

  1. Upgrade to Visual Studio 2013 Update 3.

  2. Upgrade Entity Framework to 6.1.1

  3. Modify the context configuration to use IDbSet<...> instead of DbSet<...> (I have heard that this can affect using async actions, but not apparently in my case, as I use this in my login actions, etc, as supplied by ASP.NET Identity 2 sample Nuget package).

Quite why this combination works, I have no idea. But then given the thundering silence from MS, I am probably not alone. I guess update 2 just didn't work...

awrigley
  • 13,481
  • 10
  • 83
  • 129
  • 7
    FYI I'm on update 4 and these instructions sadly didn't work - same error. – sming Nov 22 '14 at 07:06
  • Have you tried the other suggestions on here? They didn't work for me, but if what works for me doesn't work for you, then maybe what doesn't work for me will work for you? Just hoping. Quite why the MS evangelists don't pick up on these problems, eg Scott Hanselman, and write a blog post with solutions is beyond me. – awrigley Nov 22 '14 at 23:27
  • yes I've tried them all barring Farrukh's, which you state is not really answering the question. regisbsb & Math's answers don't apply since we're using inline config strings. – sming Nov 23 '14 at 05:18
  • 1
    see my answer...essentially, ensure that in web.config, the configSections element is the first element in the configuration, before the connectionStrings element – Thiago Silva Dec 10 '14 at 19:52
  • 1
    This solution worked for me, although I was having a different problem with the error message: "...To reference the existing configuration use the Entity() or ComplexType() methods." I had installed VS2013 Update 4 and EF 6.1.2. What I did differently is change the DbSet<...> to IDbSet<...> in T4 templates which you can add by right-clicking on the web project Entity Framework>Customize Reverse Engineer Templates. – Jose Jan 06 '15 at 18:08
  • This sollution worked for me with Visual Studio Express 2013 for Web and EF 6.1.2. Thanks! – ThdK Jan 19 '15 at 21:31
  • I had forgotten to add and around " – Brice May 16 '15 at 15:03
  • Changing to use IDBSet instead of DbSet is what fixed it for me. Thanks! – Treyphor Jul 04 '15 at 20:52
  • 1
    Changing DbSet to IDbSet worked for me too. Thanks :) – Laurence Frost Nov 24 '15 at 18:25
  • Tried 50 different things and this one worked for me! – Steven Edison Dec 13 '16 at 20:11
6

Solution

Make sure section

<connectionStrings>..</connectionStrings>

is after

<configSections>..</configSections>
Moji
  • 5,720
  • 2
  • 38
  • 39
4

Please run the following command in the Package Manager Console:

Uninstall-Package EntityFramework -Force

Install-Package EntityFramework

Uninstall-Package  MvcScaffolding

Install-Package MvcScaffolding
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
SKB
  • 41
  • 1
3

I had the very same issue with Visual Studio 2013 Update 3, but only for the scaffolders working with Entity Framework. The issue is seemingly caused by the incompatibility between Entity Framework 6.1.0 and the scaffolders in Visual Studio 2013 Update 2 and above.

To upgrade EF do the following:

Uninstall-Package EntityFramework -Force

Install-Package EntityFramework

This answer is borrowed from here

After the upgrade the scaffolders are working fine for me. Make sure to install the new version in every project where Entity Framework is required.

Community
  • 1
  • 1
The Victor
  • 319
  • 3
  • 13
2

n my case, I solved the issue with the connection string in the web.config.

Previuos the issue I has

  <connectionStrings configSource="Configs\ConnectionString.config"/>

and I doesnt know why, but vs cant connect to the database and fail.

after the change

<connectionStrings>
    <add name="UIBuilderContext" connectionString="metadata=res:/ ..... " />
  </connectionStrings>

and it works

Math
  • 768
  • 1
  • 8
  • 18
  • I will try that when I get time to reinstall VS 2013 Update 2 – awrigley Aug 06 '14 at 18:05
  • The connection strings are fine, no problem there, so can rule that one out. – awrigley Aug 12 '14 at 13:20
  • This fixed it for me. I had connStrings in a separate file for privacy reasons. Temporarily putting them back into the we,confi file (i.e. inline) fixed it for me (and I then moved them back as they were once I had the scaffolded controller and views). – rohancragg Nov 28 '14 at 13:00
2

This can be useful for people who haven't installed any scaffolding nuget packages in their solution.

In fact I don't have mvcscaffolding or t4scaffolding installed and got the same error message.

In my case the problem/bug was caused by changing the connection string.

Here what I had/steps to reproduce.

  • Installed Visual Studio 2013 Community Edition
  • Created MVC project
  • Created code first model
  • Edited connection string to connect to a real server, like this:

    <add name="DefaultConnection"
         connectionString="server=myserv;database=MyCustomerDB;user id=myuser;password=mypass" 
         providerName="System.Data.SqlClient" />
    

Then I enabled migrations via nuget, like this:

  • Enable-Migrations
  • Add-Migration InitialCreate
  • Update-Database
  • I started the website and I could register a user. All tables were created correctly.

Then I created a controller by using the scaffolding option:

  • right click on "Controllers" > "Add" > Controller... > MVC 5 Controller with views, using Entity Framework > selected my context and a class to be used. It worked.

Then I decided to do more code first changes and begin from scratch:

  • I changed the connection string as follows, to use localdb:

    <add name="DefaultConnection" 
         connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-Test-20141126094523.mdf;Initial Catalog=aspnet-Test-20141126094523;Integrated Security=True"
         providerName="System.Data.SqlClient" />
    

Then I went on:

  • deleted the migrations folder
  • re-enabled migrations using the same commands as above, in the nuget console
  • started thw website and registered a user
  • checked the mdf db. All tables are there, so the connection string works.
  • right click on "Controllers" > "Add" > Controller... > MVC 5 Controller with views, using Entity Framework. Selected my context and a class to be used. It did not work and this popup error appeared:

There was an error running the selected code generator: 'Exception has been thrown by the target of an invocation.'

SOLUTION:

After some investigation, what I did, is changing back the connection string in the web.config to the initial one to the "real server" (instead of localdb). I tried again to generate the controller with views. It worked!

So it seems to me a connection string problem/bug or a localdb problem... can't explain it. Maybe Visual Studio doesn't like what I did, I had to keep my old connection string...

Anyway, so now when I need scaffolding I just change the connection string to the one that works. Then to test my website I change it back to the localdb one.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
firepol
  • 1,731
  • 22
  • 39
  • I note that this does not answer the question, as my problem, as stated in the question, was different. I would not want anyone to be confused, so -1. – awrigley Dec 03 '14 at 15:28
  • I would suggest reading the FAQ on this site about how to use it. It is not intended to be a forum, with the thread swaying this way and that and diverging from the question. It is, instead, a Q&A site. Ie, you ask a question and other people suggest answers. They do not try to engage in a "conversation" about similar problems, as might happen on a forum. I don't intend to be rude or unfair, just trying to promote the correct use of this site as others did with me in the early days. – awrigley Dec 03 '14 at 15:30
  • 1
    ah ok I see, then I guess I should have published a same question, let somebody tell me it's a duplicate, then answer on my own question saying it's a different problem (same error message... different problem? Really?) and justify the duplicate because the solution is different? I love this website because I find solutions. And I don't like duplicates... anyway, thx for the feedback. I'll consider twice before posting working and useful solutions next time... – firepol Dec 04 '14 at 08:04
  • sorry, but you very clearly don't see. The error is similar or even the same, but your set up is different. You were NOT answering the question that I had asked and that is confusing to others. – awrigley Dec 04 '14 at 10:01
  • I wrote in bold "for people who haven't installed any scaffolding nuget packages". That should not really confuse people who don't apply... anyway... sorry, feel free to delete the answer. When I googled for this VS bug I arrived here and in another similar stackoverflow question. Sometimes to find the good answer one needs to do many google searches... I was only thinking to help... next time I publish on my blog... – firepol Dec 05 '14 at 08:22
2

I'll explain here a little bit more in English, so anyone can understand. Hope this helps anyone out there This occurs because Visual Studio fails to connect to the database model .

This happens when you change the name and/or the path in the class that extends DbContext and didn't change it in the Web.config file (at the outermost part of your project: the root).

Example:

Imagine you scaffolded the DbContext code:

a) You right clicked a folder in your project and added a "ADO.NET Entity Data Model", and you named it "Model1"

You get the following code:

  public class Model1 : DbContext
{
    // Your context has been configured to use a 'Model1' connection string from your application's 
    // configuration file (App.config or Web.config). By default, this connection string targets the 
    // 'Skelleton.Models.Model1' database on your LocalDb instance. 
    // 
    // If you wish to target a different database and/or database provider, modify the 'Model1' 
    // connection string in the application configuration file.
    public Model1()
        : base("name=Model1")
    {
    }

    // Add a DbSet for each entity type that you want to include in your model. For more information 
    // on configuring and using a Code First model, see http://go.microsoft.com/fwlink/?LinkId=390109.

    // public virtual DbSet<MyEntity> MyEntities { get; set; }
}

enter image description here

b) Now, you have decided that the name you've just written is plain bad, so you change it to AppContext

Your code now looks like this:

  public class AppContext : DbContext
{
    // Your context has been configured to use a 'AppContext' connection string from your application's 
    // configuration file (App.config or Web.config). By default, this connection string targets the 
    // 'Skelleton.Models.AppContext' database on your LocalDb instance. 
    // 
    // If you wish to target a different database and/or database provider, modify the 'AppContext' 
    // connection string in the application configuration file.
    public AppContext()
        : base("name=AppContext")
    {
    }

    // Add a DbSet for each entity type that you want to include in your model. For more information 
    // on configuring and using a Code First model, see http://go.microsoft.com/fwlink/?LinkId=390109.

    // public virtual DbSet<MyEntity> MyEntities { get; set; }
}

enter image description here

Then, you try to Scaffold the CRUD (Create, Read, Update, Delete) operations with views and it fails!

enter image description here

Why is that?

Well, if we go to the web.config file, we can see the following string:

 <add name="Model1" connectionString="data source=(LocalDb)\v11.0;initial catalog=Skelleton.Models.Model1;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />

(This line is usually below <add name="DefaultConnection" )

enter image description here And there is where the problem lies. You need to change Model1 for the name you've given out!

In this case, it should say "AppContext" instead of "Model1"

And where it says:

initial catalog=Skelleton.Models.Model1;

Verify that:

  1. It's the name of the .cs file that has the class

  2. The namespace (or the series of names (dot-separated) that comes before the name of your class) is the correct one. It's important to notice that you do not append to the end the ".cs" extension; just the name of your file.

It should look like this: enter image description here

Because I changed the name of the class, both internally and externally (inside it and it's file name), and did not change its location, I just rename it to AppContext

After this has been done. You can scaffold normally ;)

Hope this helps!

Jose A
  • 10,053
  • 11
  • 75
  • 108
  • Sorry, but I had not changed the model name. There is no error in my web.config. As stated clearly in the question, the problem was produced by upgrading Visual Studio 2013 to Update 2. – awrigley Feb 05 '15 at 21:48
  • @awrigley: Ah Perfect :) . Hate when those things happen. Will let the answer in there just in case someone present a similar problem. Thanks for clarifying. – Jose A Feb 06 '15 at 21:26
  • The error is not the same "There was an error running the selected code generator: 'Exception has been thrown by the target of an invocation.' – MusicAndCode Feb 07 '17 at 13:52
  • Thank you very much!, you saved my day finally. This one worked to me! – yibe Aug 10 '18 at 22:04
2

For me, I had to ensure <configSettings>, <appSettings>, & <connectionStrings> tags were NOT using a configSource attribute.

I was still able to use configSource attributes else where, such as the rewriter tag.

Cord Rehn
  • 1,119
  • 14
  • 22
  • 1
    That worked for me. Comment out the line with the configSource attribute and copy the content from the configSource file for scaffoling. – chris vietor May 04 '15 at 10:02
2

I think, the problem is due to bad configuration in web.config file.

In my case I had multiple <entityFramework> sections in web.config, and the problem resolved after I changed the configurations.

Dipen Shah
  • 25,562
  • 1
  • 32
  • 58
2

I'm on VS 2013 Update 4 and have exactly same issue. It works for me when moving connection string from external file into web.config. So I guess you could try to make sure not using configureSource attribute for connectionString when scaffolding.

My web.config before and after the change Before:

<connectionStrings configureSource="connectionStrings.config/>

After:

<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <log4net configSource="log4net.config" />
  <connectionStrings>
    <clear/>
    <add name="DefaultConnection" connectionString="Data Source=.;Initial Catalog=YourDb;Integrated Security=False;User ID=sa;Password=YourPassword!#;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
  </connectionStrings>
Peter O.
  • 32,158
  • 14
  • 82
  • 96
Dung Le
  • 91
  • 1
  • 2
1

I have performed following to solve this issue:

  1. In Package Manager check if you have MVCScffolding or T4Scaffolding (Core or pre release for vs2013)
  2. Uninstall all packaged that depend on any of MVCScaffolding or T4Scaffolding
  3. Copy CodeTemplates Folder in full (Do not replace your custom templates but make sure you have rest of the files from root of this folder. I take that you have done that part as you have customised some templates so you know where this folder is)
  4. Build Your project and close it.
  5. Restart Visual Studio under admin mode
  6. Open Package Manager Console (it should not have any errors and you can see PM> without errors.
  7. Right Click on Controller folder and choose Add->New Scaffolding Item or Choose Add->Controller both should ask which one you want and then choose MVC5 scaffold or which ever appears in list.
  8. You will then get to select your parameters if its controller you might need to choose DBContext or repository etc.

This produced the controller and relevant views for me.

I added a custom partial view called QuickView in that folder however this scaffolding procedure did not consider that and only generated views that it was doing by default. I am not sure if you need to add these custom views in a file to tell Scaffolder to generate those as well.

Farrukh Subhani
  • 2,018
  • 1
  • 17
  • 25
  • See point 2 in my question - I did not have any MVCScaffolding or T4Scaffolding installed. So your solution is not relevant. You don't mention if you have Visual Studio 2013 Update 2 installed - if you don't then you are not answering the question and you should remove your answer. – awrigley Jun 10 '14 at 21:20
  • I have VS 2013 update 2 installed. If you dont have MVCScaffolding or T4Scaffolding even then check your packages folder it might have an empty folder. If none of them is installed you can start from step 3. I had none of these installed and had this issue when i updated VS to update 2. I had to copy all Templates (deleted VB ones only) and kept all files as it is and followed above and it worked. Then I installed MVCMailer and Package Manager gave errors on init so had to remove them and retry and it worked again. – Farrukh Subhani Jun 11 '14 at 10:31
  • I have added MVCMailer package today and it added T4Scaffolding.Core again and I reproduced the same error, after removing both packages the error still remains and after i followed step 4-8 Scaffolder worked again. – Farrukh Subhani Jun 12 '14 at 12:01
  • I have looked at your suggestions in detail. Essentially, they do NOT address the issue that I have. They address the issue where MVCScaffolding or T4Scaffolding were installed. That is not my case. Steps 3 onwards are nothing other than the standard instructions for scaffolding controllers. That is what I do anyway. Sorry, this is definitely not the solution to my problem. – awrigley Jun 13 '14 at 08:53
0

For me what worked was to make sure the <configSections> node in the web.config file was the first node immediately after <configuration> node.

Initially, when I added my connectionStrings, I had actually placed it before the configSections, which made the Scaffold tool break.

Seems like when the scaffolding runs and tries to grab connection info, it expects the config section for the entityFramework node to be there already so it know what DB provider to use, but when I had the connection string before configSections, it didn't know to use LocalDB (which is what my conn string was using).

Thiago Silva
  • 14,183
  • 3
  • 36
  • 46
0

I have been having this same problem in update 4. I found that the problem came from the <configSections></configSections> not having a section name defined. The fix I put in between the tags is as follows and all the errors were fixed:

<section name="entityFramework" 
         type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, 
               EntityFramework, Version=6.0.0.0, Culture=neutral, 
               PublicKeyToken=b77a5c561934e089" requirePermission="false" />

Build the project and everything should work. Cheers!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
RyanH
  • 1
0

I'm running VS 2015RC the last one before final cut. Not to discount any of the solutions here. My solution was under nugget package manager and updated my Microsoft.Aspnet.Mvc 5.2.3 package and that fix my issue. I hope that helps anyone using VS 2015.

RockingCoder
  • 31
  • 1
  • 8
0

i used Initializer and when remove/comment Initializer from myDbContext constructer , scaffolding work fine

public myDbContext () : base("name=DefaultConnection")
    {

        //Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DastanakDbContext>());
        //Database.Initialize(true);
    }
AminM
  • 1,658
  • 4
  • 32
  • 48