For what it’s worth, the below solution is what worked for me.
My Setup:
First of all my project setup was different. I had a MyProject.Data and MyProject, and I was trying to scaffold «API Controller with actions, using Entity Framework» on to my API folder in MyProject, and I was getting the error in question. I was using .net 3.1.
Solution:
I had to downgrade all the below nuget packages installed on MyProject.Data project
Before downgrade:
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.2">
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.2">
After downgrade:
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.11">
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.11">
Then tried again to use scaffolding and it just worked!!
After scaffolding MyProject had the below nuget package versions installed:
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="3.1.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.11"/>
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.4" />
The main problem was that no errors were displayed other than the one that shows up on the dialog box or does not even point us to any logs or nor any helpful documentation are available. If anyone finds one please attach it to this answer. It was very frustrating and this almost ate away half-day of my weekend 
Hope it helps someone. Happy coding!!
When I was creating a Controller and a View by MVC Controller with views, using Entity Framework I got an error.
The Error is:
There was an error running the selected code generator: ‘Could not
load file or assembly Microsoft.EntityFrameworkCore, version =
2.0.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60’ the located assembly’s manifest definition does not match the assembly reference
Creating MVC Controller with views, using Entity Framework:

How can I solve this problem?
I use Visual Studio Version 15.5.2 and version of Microsoft.AspNetCore.All is 2.0.0
asked Jan 3, 2018 at 16:14
![]()
I updated the Microsoft.AspNetCore.All to version 2.0.3 and now it does work right.
answered Jan 3, 2018 at 16:25
![]()
x19x19
8,17715 gold badges65 silver badges126 bronze badges
1
Go to NugetPackage Manager and update the Microsoft.AspNetCore.All package
answered Mar 28, 2018 at 12:21
SajithdSajithd
5291 gold badge5 silver badges11 bronze badges
For me none of the above solutions worked. I had to add Microsoft.EntityFrameworkCore and Microsoft.EntityFrameworkCore.Design packages even though I have Microsoft.AspNetCore.All package added to my project.
Edit project in VS 2017 and add these lines
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.0.3" />
Trinidad
2,7452 gold badges24 silver badges43 bronze badges
answered Jul 29, 2019 at 5:12
![]()
CrennotechCrennotech
5215 silver badges8 bronze badges
1
Update your packages or it can happen when you have an older SDK. Download a new .NET Core SDK and runtime from www.microsoft.com/net
answered Jan 16, 2019 at 9:15
juFojuFo
17.6k10 gold badges105 silver badges140 bronze badges
I had a similar issue but mine was something with the versioning of visual studio.
I went to Visual Studio Installer and it notified me that I had to restart my computer
answered Jan 5, 2019 at 3:14
![]()
I got this same error:

Running Preview 2019 and .NET Core 3.
I moved the Nuget pkg sources up in my list.
I was attemping to add a new Controller and I would get this error every time.
I also noticed that for some reason I chose not to set up SSL but I had the setting in my launchSettings.json.
I deleted the setting for ssl and built the app and ran it.
After the successful run I could add the Controller without the error.
answered May 1, 2019 at 17:29
![]()
raddevusraddevus
8,2117 gold badges65 silver badges84 bronze badges

Follow these Steps:-
From Tools
- Select NuGet Package Manager
-> Manage NuGet Packages For Solution
click on ->Updates Select the checkbox Select All
->Select Your Project from right hand side -> Click on Upadate
answered Oct 9, 2020 at 5:10
![]()
Having the same error, after downloaded VS2019″PREVIEW» and then opened a core 3.0 project there I was able to scaffold content no errors at all..
answered Aug 7, 2019 at 12:53
![]()
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
- Pick a username
- Email Address
- Password
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
I’m creating a new view off of a model.
The error message I am getting is
Error
There was an error running the selected code generator:
‘Access to the path
‘C:UsersXXXXXXXAppDataLocalTempSOMEGUIDEntityFramework.dll’ is denied’.
I am running VS 2013 as administrator.
I looked at Is MvcScaffolding compatible with VS 2013 RC by command line? but this didn’t seem to resolve the issue.
VS2013
C#5
MVC5
Brand new project started in VS 2013.
asked Nov 12, 2013 at 4:25
![]()
4
VS2013 Error: There was an error running the selected code generator:
‘ A configuration for type ‘SolutionName.Model.SalesOrder’ has already
been added …’
I had this problem while working through a Pluralsight Course «Parent-Child Data with EF, MVC, Knockout, Ajax, and Validation». I was trying to add a New Scaffolded Item using the template MVC 5 Controller with views, using Entity Framework.
The Data Context class I was using including an override of the OnModelCreating method. The override was required to add some explicit database column configurations where the EF defaults were not adequate. This override was simple, worked and no bugs, but (as noted above) it did interfere with the Controller scaffolding code generation.
Solution that worked for me:
1 — I removed (commented out) my OnModelCreating override and the scaffolding template completed with no error messages — my controller code was generated as expected.
2 — However, trying to build the project choked because ‘The model had changed’. Since my controller code was was now properly generated, I restored (un-commented) the OnModelCreating override and the project built and ran successfully.
![]()
Liam
26.7k27 gold badges120 silver badges183 bronze badges
answered Aug 16, 2014 at 22:31
Bill BBill B
3513 silver badges4 bronze badges
3
Problem was with a corrupted web.config and package directory.
I created the new project, and copied my code files over to the new working project, I later went back and ran diffs on the config files and a folder diff on the project itself.
The problem was that the updates had highly junked up my config file with lots of update artifacts that I ended up clearing out.
The second problem was that the old project also kept hanging onto older DLLs that were supposed to be wiped with the application of the Nuget package. So I wiped the obj and bin folders, then the package folder. After that was done, I was able to get the older project repaired and building cleanly.
I have not looked into why the config file or the package folder was so borked, but I’m assuming it is one of two things.
- Possibly the nuget package has a flaw
- The TFS source control blocked nuget from properly updating the various dependencies.
Since then, before applying any updates, I check out everything. However, since I have not updated EF in a while, I no evidence that this has resolved my EF or scaffolding issue.
answered Jan 22, 2014 at 1:55
![]()
Brian WebbBrian Webb
1,1361 gold badge14 silver badges29 bronze badges
2
I was able to resolve this issue and have a little better understanding of what was going on. The best part is that I am able to recreate the issue and fix it to be sure of my explanation here.
The resolution was to install exactly same version of Entity Framework for both Data Access Layer project and the Web Project.
My data access layer had Entity Framework v6.0.2 installed using NuGet, the web project did not have Entity Framework installed. When trying to create a Web API Controller with Entity Framework template Entity Framework gets installed automatically but its one of the older version 6.0.0. I was surprised to see two version of Entity Framework installed, newer on my Data Layer project and older on my Web Project. Once, I removed the older version and installed the newer version on Web Project the problem went away.
answered Mar 7, 2014 at 20:09
isinghisingh
1411 silver badge5 bronze badges
2
I tried every answer on every website I found, and nothing worked… until this. Posting late in case anyone like me comes along and has the same frustrating experience as I have.
My issue was similar to many here, generic error message when trying to use scaffolding to try and add a new controller (ef6, webapi). I initially was able to use scaffolding for about 15 controllers, after that it just stopped working one day.
Final Solution:
- Open your working folder on your hard drive for your solution.
- Delete everything inside the BIN folder
- Delete everything inside the OBJ folder
- Clean Solution, Rebuild Solution, Add Controller via scaffolding
Voila! (for me)
answered May 13, 2015 at 14:46
![]()
erikruniaerikrunia
2,3591 gold badge15 silver badges21 bronze badges
1
I checked all my projects and each had the same version of Entity Framework. In my case, the problem was that one of my projects was targeting .Net 4.0 while the rest were .Net 4.5.
Solution:
- For each project in solution Project->Properties->Application: Set Target Framework to .Net 4.5 (or whatever you need).
- Tools->Manage NuGet Package for Solution. Find Installed “Entity Framework”. And click Manage. Uncheck all projects (note the projects that require EF). Now, Re-Manage EF and check that projects that you need.
- Clean and Rebuild Solution.
![]()
Jess
23k19 gold badges121 silver badges140 bronze badges
answered May 1, 2014 at 12:52
![]()
RitchieDRitchieD
1,81121 silver badges21 bronze badges
0
This is typically caused by an invalid Web.config file. I had the same problem and it turned out I inadvertently changed the HTML comment block <!-- --> to a server side comment block @* *@ (through a Replace All action).
And in case you are developing a WinForms application, try to look to App.config.
answered May 25, 2014 at 11:17
Moslem Ben DhaouMoslem Ben Dhaou
6,8477 gold badges62 silver badges92 bronze badges
2
I have the exact same problem.
First encountered this while following along the Pluralsight Course «Parent-Child Data with EF, MVC, Knockout, Ajax, and Validation».
I am using MVC 5, EF 6.1.1 and framework 4.5.2.
Even after updating my VS2013 to update 4, this error still persisted.
Was able to circumvent this annoying problem by changing the DbSet to IDbSet inside the DbContext class.
Answer was originally from here.
//From
public DbSet SalesOrders { get; set; }
//To
public IDbSet SalesOrders { get; set; }
answered Nov 14, 2014 at 9:33
scyuscyu
514 bronze badges
What worked for me to resolve this: Close Solution, And open the project by clicking project file and not the solution file, add your controller, and bobs your uncle
answered Mar 6, 2014 at 9:52
Gerrie PretoriusGerrie Pretorius
3,1312 gold badges30 silver badges34 bronze badges
0
None of the above helped for me.
I found that the cause of my problem was overriding OnModelCreating in my context class that the scaffold item was dependent on. By commenting out this method, then the scaffolding works.
I do wish Microsoft would release less buggy code.
answered Aug 12, 2014 at 0:56
![]()
2
There was an error running the selected code generator:
‘Failed to upgrade dependency information for the project. Please restore the project and try again.’
Steps:
- Go to your project and update all NuGet packages to latest version.
- Build your application till Build success.
- Close solution and reopen same.
- And try to add file like controller, class, etc.

![]()
TylerH
20.4k62 gold badges75 silver badges96 bronze badges
answered Aug 2, 2019 at 8:06
![]()
0
I have seen this error with a new MVC5 project when referencing a model from a different project. Checking the path, EntityFramework.dll did exist. It was read-only though. Process monitor showed that there was an error attempting to delete the file. Setting the EntityFramework.dll in my packages folder (copy stored in source control) to writeable got around this error but brought up another one saying that it couldn’t load the EntityFramework assembly because it didn’t match the one referenced. My model class was defined in a different project that was using an older version of the entity framework. The MVC5 project was referencing EF 6 while the model was from a project references EF 4.4. Upgrading to EF 6 in the model’s project fixed it for me.
answered Nov 21, 2013 at 9:15
LindseyLindsey
4514 silver badges3 bronze badges
For us it has something to do with build configurations, where we have a Debug|x64 build configuration that we had recently switched to using, which in retrospect seemed to be when the scaffolding stopped working.
(I suspect that there are at least 10 different things that can cause this, as evidenced by the various answers on SO that some people find to work for them—but which don’t work for others, so I’m not suggesting my solution will work for everyone).
What worked for us (using VS 2013 Express for Web on 64 bit Windows 7):
It (scaffolding) was NOT working in Debug|x64 Build configuration. But doing the following (and it seems like every step is necessary—couldn’t figure out how to do it in a more streamlined way) seems to work for us.
- First, switch to Debug|x86—use Solution (right-click) Configuration Manager for all the projects in your solution. (Debug|Any CPU may also work).
- Clean your solution.
- Shut down Visual Studio. (cannot get it to work if I skip this).
- Open Visual Studio.
- Open your solution.
- Build your solution.
- Now try adding scaffolding items; for us, it worked at this point, we no longer got the error message saying something about «There was an error running the selected code generator».
If you need to switch back to a scaffolding-non-working build configuration, you can do so, after you’ve scaffolded everything you need to for the moment. We switched back to our Debug|x64 after scaffolding what we needed to.
answered Mar 7, 2015 at 23:00
DWrightDWright
9,2284 gold badges36 silver badges53 bronze badges
0
I had this problem when trying to add an Api Controller to my MVC ASP.NET web app for a completely different reason than the other answers given. I had accidentally included a StringLength attribute with an IndexAttribute declaration for an integer property due to a copy and paste operation:
[Index]
[IndexAttribute("NumTrainingPasses", 0), StringLength(50)]
public int NumTrainingPasses { get; set; }
Once I got rid of the IndexAttribute declaration I was able to add an Api Controller for the Model that contained the offending property (NumTrainingPasses).
To help the search engines, here is the full error message I got before I fixed the problem:
There was an error running the selected code generator:
Unable to retrieve metadata for ‘Owner.Models.MainRecord’. The property
‘NumTrainingPasses’ is not a String or Byte array. Length can only be
configured for String or Byte array properties.
answered Jul 15, 2015 at 20:10
Robert OschlerRobert Oschler
14.1k18 gold badges90 silver badges224 bronze badges
This is usually related to a format of your Web.config
Rebuild solution and lookup under Errors, tab Messages.
If you have any format problems with a web.config you will see it there.
Fix it and try again.
Example: I had connectionstring instead of connectionString
![]()
bummi
27k13 gold badges62 silver badges101 bronze badges
answered Dec 12, 2016 at 20:00
MarkoMarko
1,8641 gold badge21 silver badges36 bronze badges
My issue was similar to many experience here, generic error message when trying to add a new view or use scaffolding to add a new controller.
I found out that MVC 5 and EF 6 modelbuilder are not good friends:
My Solution:
- Comment out modelBuilder in your Context class.
- Clean Solution, Rebuild Solution.
- Add view and Controller via scaffolding
- Uncomment modelbuilder.
![]()
TylerH
20.4k62 gold badges75 silver badges96 bronze badges
answered May 15, 2016 at 10:22
![]()
In case it helps anyone, I renamed the namespace that the model resided in, then rebuilt the project, then renamed it back again, and rebuilt, and then it worked.
answered Feb 3, 2014 at 14:45
Adam MarshallAdam Marshall
2,8718 gold badges40 silver badges78 bronze badges
I often run into this error working with MVC5 and EF when I create the models and context in a separate project (My data access layer) and I forget to add the context connection string to the MVC project’s Web.Config.
answered Dec 6, 2014 at 6:53
John SJohn S
7,76121 gold badges74 silver badges139 bronze badges
I am also having this issue with MSVS2013 Update 4 and EF 6.0
The message I was getting was:
there was an error running the selected code generator.
A configuration for type XXXX has already been added ...[]
I have a model with around 10 classes. I scaffolded elements at the beginning of the project with no problems.
After some days adding functionality, I tried to scaffold another class from the model, but an error was keeping me from doing it.
I have tried to update MSVS from update 2 to update 4, comment out my OnModelCreating method and other ideas proposed with no luck.
As a temporary way to continue with the project, I created a different asp.net project, pasted there my model classes (I am using fluent api, so there is little annotation on them) and successfully created my controller and views.
After that, I pasted back the created classes to the original project and corrected some mistakes (mainly dbset names).
It seems to be working, although I suppose that I will still find mistakes related to relationships between classes (due to the lack of fluent configuration when created).
I hope this helps to other users.
answered Feb 25, 2015 at 12:05
jmcmjmcm
235 bronze badges
This happened to me when I attempted to create a new scaffold outside of the top level folder for a given Area.
- MyArea
| — File.cs (tried to create a new scaffold here. Failure.)
I simply re-selected my area and the problem went away:
- AyArea (Add => new scaffold item)
Note that after scaffold generation you are taken to a place where you will not be able to create a new scaffold without re-selecting the area first (in VS 2013 at least).
answered Apr 20, 2015 at 15:51
P.Brian.MackeyP.Brian.Mackey
42.6k65 gold badges231 silver badges344 bronze badges
- vs2013 update 4
- ef 5.0.0
- ibm db2connector 10.5 fp 5
change the web.config file as such:
removed the provider/s from ef tag:
<entityFramework>
</entityFramework>
added connection string tags under config sections:
</configSections>
<connectionStrings>
<add name=".." connectionString="..." providerName="System.Data.EntityClient" />
</connectionStrings>
answered Jun 28, 2015 at 4:02
![]()
I had the same problem when in my MVC app EF reference property (in Properties window) «Specific version» was marked as False and in my other project (containing DBContext and models) which was refrenced from MVC app that EF reference property was marked as True. When I marked it as False everything was fine.
answered Nov 15, 2015 at 11:02
In my case, I was trying to scaffold Identity elements and none of the above worked. The solution was simply to open Visual Studio with Administrator privileges.
![]()
TylerH
20.4k62 gold badges75 silver badges96 bronze badges
answered Jan 8, 2020 at 19:01
![]()
Hugo Nava KoppHugo Nava Kopp
2,7872 gold badges24 silver badges41 bronze badges
1
Rebuild the solution works for me. before rebuild, I find references number of my ‘ApplicationDbContext’ is zero, that is impossible, so rebuild solution, everything is OK now.
answered Sep 10, 2014 at 10:08
1
I had this issue in VS 2017. I had Platform target (in project properties>Build>General) set to «x64». Scaffolding started working after changing it to «Any CPU».
answered Mar 27, 2019 at 9:51
![]()
billwbillw
1181 silver badge8 bronze badges
It may be due to differences in the versions of nuget packages. See if you have this by going to dependencies->nuget packages folder in your solution. Try installing all of them of a single version and restart the visual studio after cleaning the componentmodelcache folder as mentioned above. This should the get the work done for you.
answered May 30, 2020 at 9:57
![]()
1
I’m creating a new view off of a model.
The error message I am getting is
Error
There was an error running the selected code generator:
‘Access to the path
‘C:UsersXXXXXXXAppDataLocalTempSOMEGUIDEntityFramework.dll’ is denied’.
I am running VS 2013 as administrator.
I looked at Is MvcScaffolding compatible with VS 2013 RC by command line? but this didn’t seem to resolve the issue.
VS2013
C#5
MVC5
Brand new project started in VS 2013.
asked Nov 12, 2013 at 4:25
![]()
4
VS2013 Error: There was an error running the selected code generator:
‘ A configuration for type ‘SolutionName.Model.SalesOrder’ has already
been added …’
I had this problem while working through a Pluralsight Course «Parent-Child Data with EF, MVC, Knockout, Ajax, and Validation». I was trying to add a New Scaffolded Item using the template MVC 5 Controller with views, using Entity Framework.
The Data Context class I was using including an override of the OnModelCreating method. The override was required to add some explicit database column configurations where the EF defaults were not adequate. This override was simple, worked and no bugs, but (as noted above) it did interfere with the Controller scaffolding code generation.
Solution that worked for me:
1 — I removed (commented out) my OnModelCreating override and the scaffolding template completed with no error messages — my controller code was generated as expected.
2 — However, trying to build the project choked because ‘The model had changed’. Since my controller code was was now properly generated, I restored (un-commented) the OnModelCreating override and the project built and ran successfully.
![]()
Liam
26.7k27 gold badges120 silver badges183 bronze badges
answered Aug 16, 2014 at 22:31
Bill BBill B
3513 silver badges4 bronze badges
3
Problem was with a corrupted web.config and package directory.
I created the new project, and copied my code files over to the new working project, I later went back and ran diffs on the config files and a folder diff on the project itself.
The problem was that the updates had highly junked up my config file with lots of update artifacts that I ended up clearing out.
The second problem was that the old project also kept hanging onto older DLLs that were supposed to be wiped with the application of the Nuget package. So I wiped the obj and bin folders, then the package folder. After that was done, I was able to get the older project repaired and building cleanly.
I have not looked into why the config file or the package folder was so borked, but I’m assuming it is one of two things.
- Possibly the nuget package has a flaw
- The TFS source control blocked nuget from properly updating the various dependencies.
Since then, before applying any updates, I check out everything. However, since I have not updated EF in a while, I no evidence that this has resolved my EF or scaffolding issue.
answered Jan 22, 2014 at 1:55
![]()
Brian WebbBrian Webb
1,1361 gold badge14 silver badges29 bronze badges
2
I was able to resolve this issue and have a little better understanding of what was going on. The best part is that I am able to recreate the issue and fix it to be sure of my explanation here.
The resolution was to install exactly same version of Entity Framework for both Data Access Layer project and the Web Project.
My data access layer had Entity Framework v6.0.2 installed using NuGet, the web project did not have Entity Framework installed. When trying to create a Web API Controller with Entity Framework template Entity Framework gets installed automatically but its one of the older version 6.0.0. I was surprised to see two version of Entity Framework installed, newer on my Data Layer project and older on my Web Project. Once, I removed the older version and installed the newer version on Web Project the problem went away.
answered Mar 7, 2014 at 20:09
isinghisingh
1411 silver badge5 bronze badges
2
I tried every answer on every website I found, and nothing worked… until this. Posting late in case anyone like me comes along and has the same frustrating experience as I have.
My issue was similar to many here, generic error message when trying to use scaffolding to try and add a new controller (ef6, webapi). I initially was able to use scaffolding for about 15 controllers, after that it just stopped working one day.
Final Solution:
- Open your working folder on your hard drive for your solution.
- Delete everything inside the BIN folder
- Delete everything inside the OBJ folder
- Clean Solution, Rebuild Solution, Add Controller via scaffolding
Voila! (for me)
answered May 13, 2015 at 14:46
![]()
erikruniaerikrunia
2,3591 gold badge15 silver badges21 bronze badges
1
I checked all my projects and each had the same version of Entity Framework. In my case, the problem was that one of my projects was targeting .Net 4.0 while the rest were .Net 4.5.
Solution:
- For each project in solution Project->Properties->Application: Set Target Framework to .Net 4.5 (or whatever you need).
- Tools->Manage NuGet Package for Solution. Find Installed “Entity Framework”. And click Manage. Uncheck all projects (note the projects that require EF). Now, Re-Manage EF and check that projects that you need.
- Clean and Rebuild Solution.
![]()
Jess
23k19 gold badges121 silver badges140 bronze badges
answered May 1, 2014 at 12:52
![]()
RitchieDRitchieD
1,81121 silver badges21 bronze badges
0
This is typically caused by an invalid Web.config file. I had the same problem and it turned out I inadvertently changed the HTML comment block <!-- --> to a server side comment block @* *@ (through a Replace All action).
And in case you are developing a WinForms application, try to look to App.config.
answered May 25, 2014 at 11:17
Moslem Ben DhaouMoslem Ben Dhaou
6,8477 gold badges62 silver badges92 bronze badges
2
I have the exact same problem.
First encountered this while following along the Pluralsight Course «Parent-Child Data with EF, MVC, Knockout, Ajax, and Validation».
I am using MVC 5, EF 6.1.1 and framework 4.5.2.
Even after updating my VS2013 to update 4, this error still persisted.
Was able to circumvent this annoying problem by changing the DbSet to IDbSet inside the DbContext class.
Answer was originally from here.
//From
public DbSet SalesOrders { get; set; }
//To
public IDbSet SalesOrders { get; set; }
answered Nov 14, 2014 at 9:33
scyuscyu
514 bronze badges
What worked for me to resolve this: Close Solution, And open the project by clicking project file and not the solution file, add your controller, and bobs your uncle
answered Mar 6, 2014 at 9:52
Gerrie PretoriusGerrie Pretorius
3,1312 gold badges30 silver badges34 bronze badges
0
None of the above helped for me.
I found that the cause of my problem was overriding OnModelCreating in my context class that the scaffold item was dependent on. By commenting out this method, then the scaffolding works.
I do wish Microsoft would release less buggy code.
answered Aug 12, 2014 at 0:56
![]()
2
There was an error running the selected code generator:
‘Failed to upgrade dependency information for the project. Please restore the project and try again.’
Steps:
- Go to your project and update all NuGet packages to latest version.
- Build your application till Build success.
- Close solution and reopen same.
- And try to add file like controller, class, etc.

![]()
TylerH
20.4k62 gold badges75 silver badges96 bronze badges
answered Aug 2, 2019 at 8:06
![]()
0
I have seen this error with a new MVC5 project when referencing a model from a different project. Checking the path, EntityFramework.dll did exist. It was read-only though. Process monitor showed that there was an error attempting to delete the file. Setting the EntityFramework.dll in my packages folder (copy stored in source control) to writeable got around this error but brought up another one saying that it couldn’t load the EntityFramework assembly because it didn’t match the one referenced. My model class was defined in a different project that was using an older version of the entity framework. The MVC5 project was referencing EF 6 while the model was from a project references EF 4.4. Upgrading to EF 6 in the model’s project fixed it for me.
answered Nov 21, 2013 at 9:15
LindseyLindsey
4514 silver badges3 bronze badges
For us it has something to do with build configurations, where we have a Debug|x64 build configuration that we had recently switched to using, which in retrospect seemed to be when the scaffolding stopped working.
(I suspect that there are at least 10 different things that can cause this, as evidenced by the various answers on SO that some people find to work for them—but which don’t work for others, so I’m not suggesting my solution will work for everyone).
What worked for us (using VS 2013 Express for Web on 64 bit Windows 7):
It (scaffolding) was NOT working in Debug|x64 Build configuration. But doing the following (and it seems like every step is necessary—couldn’t figure out how to do it in a more streamlined way) seems to work for us.
- First, switch to Debug|x86—use Solution (right-click) Configuration Manager for all the projects in your solution. (Debug|Any CPU may also work).
- Clean your solution.
- Shut down Visual Studio. (cannot get it to work if I skip this).
- Open Visual Studio.
- Open your solution.
- Build your solution.
- Now try adding scaffolding items; for us, it worked at this point, we no longer got the error message saying something about «There was an error running the selected code generator».
If you need to switch back to a scaffolding-non-working build configuration, you can do so, after you’ve scaffolded everything you need to for the moment. We switched back to our Debug|x64 after scaffolding what we needed to.
answered Mar 7, 2015 at 23:00
DWrightDWright
9,2284 gold badges36 silver badges53 bronze badges
0
I had this problem when trying to add an Api Controller to my MVC ASP.NET web app for a completely different reason than the other answers given. I had accidentally included a StringLength attribute with an IndexAttribute declaration for an integer property due to a copy and paste operation:
[Index]
[IndexAttribute("NumTrainingPasses", 0), StringLength(50)]
public int NumTrainingPasses { get; set; }
Once I got rid of the IndexAttribute declaration I was able to add an Api Controller for the Model that contained the offending property (NumTrainingPasses).
To help the search engines, here is the full error message I got before I fixed the problem:
There was an error running the selected code generator:
Unable to retrieve metadata for ‘Owner.Models.MainRecord’. The property
‘NumTrainingPasses’ is not a String or Byte array. Length can only be
configured for String or Byte array properties.
answered Jul 15, 2015 at 20:10
Robert OschlerRobert Oschler
14.1k18 gold badges90 silver badges224 bronze badges
This is usually related to a format of your Web.config
Rebuild solution and lookup under Errors, tab Messages.
If you have any format problems with a web.config you will see it there.
Fix it and try again.
Example: I had connectionstring instead of connectionString
![]()
bummi
27k13 gold badges62 silver badges101 bronze badges
answered Dec 12, 2016 at 20:00
MarkoMarko
1,8641 gold badge21 silver badges36 bronze badges
My issue was similar to many experience here, generic error message when trying to add a new view or use scaffolding to add a new controller.
I found out that MVC 5 and EF 6 modelbuilder are not good friends:
My Solution:
- Comment out modelBuilder in your Context class.
- Clean Solution, Rebuild Solution.
- Add view and Controller via scaffolding
- Uncomment modelbuilder.
![]()
TylerH
20.4k62 gold badges75 silver badges96 bronze badges
answered May 15, 2016 at 10:22
![]()
In case it helps anyone, I renamed the namespace that the model resided in, then rebuilt the project, then renamed it back again, and rebuilt, and then it worked.
answered Feb 3, 2014 at 14:45
Adam MarshallAdam Marshall
2,8718 gold badges40 silver badges78 bronze badges
I often run into this error working with MVC5 and EF when I create the models and context in a separate project (My data access layer) and I forget to add the context connection string to the MVC project’s Web.Config.
answered Dec 6, 2014 at 6:53
John SJohn S
7,76121 gold badges74 silver badges139 bronze badges
I am also having this issue with MSVS2013 Update 4 and EF 6.0
The message I was getting was:
there was an error running the selected code generator.
A configuration for type XXXX has already been added ...[]
I have a model with around 10 classes. I scaffolded elements at the beginning of the project with no problems.
After some days adding functionality, I tried to scaffold another class from the model, but an error was keeping me from doing it.
I have tried to update MSVS from update 2 to update 4, comment out my OnModelCreating method and other ideas proposed with no luck.
As a temporary way to continue with the project, I created a different asp.net project, pasted there my model classes (I am using fluent api, so there is little annotation on them) and successfully created my controller and views.
After that, I pasted back the created classes to the original project and corrected some mistakes (mainly dbset names).
It seems to be working, although I suppose that I will still find mistakes related to relationships between classes (due to the lack of fluent configuration when created).
I hope this helps to other users.
answered Feb 25, 2015 at 12:05
jmcmjmcm
235 bronze badges
This happened to me when I attempted to create a new scaffold outside of the top level folder for a given Area.
- MyArea
| — File.cs (tried to create a new scaffold here. Failure.)
I simply re-selected my area and the problem went away:
- AyArea (Add => new scaffold item)
Note that after scaffold generation you are taken to a place where you will not be able to create a new scaffold without re-selecting the area first (in VS 2013 at least).
answered Apr 20, 2015 at 15:51
P.Brian.MackeyP.Brian.Mackey
42.6k65 gold badges231 silver badges344 bronze badges
- vs2013 update 4
- ef 5.0.0
- ibm db2connector 10.5 fp 5
change the web.config file as such:
removed the provider/s from ef tag:
<entityFramework>
</entityFramework>
added connection string tags under config sections:
</configSections>
<connectionStrings>
<add name=".." connectionString="..." providerName="System.Data.EntityClient" />
</connectionStrings>
answered Jun 28, 2015 at 4:02
![]()
I had the same problem when in my MVC app EF reference property (in Properties window) «Specific version» was marked as False and in my other project (containing DBContext and models) which was refrenced from MVC app that EF reference property was marked as True. When I marked it as False everything was fine.
answered Nov 15, 2015 at 11:02
In my case, I was trying to scaffold Identity elements and none of the above worked. The solution was simply to open Visual Studio with Administrator privileges.
![]()
TylerH
20.4k62 gold badges75 silver badges96 bronze badges
answered Jan 8, 2020 at 19:01
![]()
Hugo Nava KoppHugo Nava Kopp
2,7872 gold badges24 silver badges41 bronze badges
1
Rebuild the solution works for me. before rebuild, I find references number of my ‘ApplicationDbContext’ is zero, that is impossible, so rebuild solution, everything is OK now.
answered Sep 10, 2014 at 10:08
1
I had this issue in VS 2017. I had Platform target (in project properties>Build>General) set to «x64». Scaffolding started working after changing it to «Any CPU».
answered Mar 27, 2019 at 9:51
![]()
billwbillw
1181 silver badge8 bronze badges
It may be due to differences in the versions of nuget packages. See if you have this by going to dependencies->nuget packages folder in your solution. Try installing all of them of a single version and restart the visual studio after cleaning the componentmodelcache folder as mentioned above. This should the get the work done for you.
answered May 30, 2020 at 9:57
![]()
1
I’m following a video tutorial where I’m required to create an empty ASP.NET Web Application with MVC, using Visual Studio 2015, being new to ASP.NET world, I’m following step by step.
I got my project created well, next step adding a View from an existing Controller, I got hit by a messagebox error saying :
Error :
There was an error running the selected code generator:
‘Invalid pointer (Exception from HRESULT:0x80004003(E_POINTER))’
I Googled the problem, found similar issues, but none led to a clear solution, some similar problems were issued by anterior version of VisualStudio, but as I said none with a clear solution.
To clarify what I experienced, here’s what I’ve done step by step :
Chosen a ASP.NET Web Application :

Chosen Empty Template with MVC checked :

Tried to Add View from a Controller :

Some settings …

The Error :

What’s causing this problem and What is the solution for it ?
Update :
It turns out that even by trying to add the View manually I get the same error, adding a view is all ways impossible !
asked Jan 25, 2016 at 12:25
![]()
AymenDaoudiAymenDaoudi
7,4919 gold badges52 silver badges83 bronze badges
2
Try clearing the ComponentModelCache, the cache will rebuild next time VS is launched.
- Close Visual Studio
- Delete everything in this folder C:Users
[your users name]AppDataLocalMicrosoftVisualStudio14.0ComponentModelCache - Restart Visual Studio
14.0 is for visual studio 2015. This will work for other versions also.
VSB
9,38716 gold badges69 silver badges137 bronze badges
answered Mar 5, 2016 at 14:06
longdaylongday
3,9754 gold badges28 silver badges35 bronze badges
8
I had this issue with a different error message «-1 is outs the bounds of..»
The only thing that worked for me, was to remove the project from the solution by right clicking the project and selecting ‘Remove’. Then right click the solution, Add Existing Project, and selecting the project to reload it into the solution.
After reloading the project, I can now add views again.
answered Aug 29, 2019 at 16:20
![]()
lucky.expertlucky.expert
6711 gold badge15 silver badges23 bronze badges
1
I have the same error but in VS 2017 when I create a controller. I did it in the same way as @sh.alawneh wrote. Also, I tried to do what @longday wrote. But It didn’t work. Then I tried in another way:
- Right click on the target folder.
- From the list, choose Add => New Item.
There I choose a new controller and it works fine.
Maybe I’ll help someone.
answered Dec 10, 2018 at 16:41
Maksym LabutinMaksym Labutin
5631 gold badge7 silver badges17 bronze badges
2
Follow these steps to add a view in a different way than the typical way:
- 1) Open Visual studio.
- 2) Create/open your project.
- 3) Go to Solution Explorer.
- 4) Right click on the target folder.
- 5) From the list, choose Add.
- 6) From the child list, choose MVC View Page (Razor) or MVC View Page with layout (Razor).
- 7) If you select the second choice from the previous step, you should choose a layout page for your view from the pop up window.
-
That’s it!
If you cannot open the view that you are created, simply right click on the view file, choose Open with, and select HTML (web forms) editor then okay.
dorukayhan
1,5054 gold badges23 silver badges27 bronze badges
answered Jul 27, 2016 at 17:17
sh.alawnehsh.alawneh
6195 silver badges13 bronze badges
1
In my case helped the following:
- Restart VS
- Solution Explorer => Right click on solution => Rebuild solution
answered Nov 29, 2020 at 17:33
essentialessential
6181 gold badge6 silver badges19 bronze badges
1
I solved this problem in this way
first I had Entity frameworks with the latest version 5.0.5

and the code generation package with version 5.0.2

so I just uninstalled Entity frameworks and install version 5.0.2 as the same for code generation package
and its worked
answered May 3, 2021 at 19:42
NourNour
1188 bronze badges
1
Right-click on the project under the solution and click unload Project,
you will see that the project is unloaded, so now re right-click on it and press load project
then try to add your controller
answered Nov 19, 2019 at 12:36
![]()
2
Lets assume you are using a datacontext in a DLL, well, it was my case, and I dont know why I have the same error that you describe, I solve it creating a datacontextLocal on the backend project. then I pass the Dbset to the correct datacontext and delete the local (you can let it there if you want, can be helpfull in the future
if you ready are using it in local datacontext, create a new one and then pass the Dbset to the correct one
answered Sep 29, 2017 at 11:59
sGermosensGermosen
3443 silver badges14 bronze badges
In ASP.NET Core check if you have the Microsoft.VisualStudio.Web.CodeGeneration.Tools nuget package and it corresponds to your project version.
answered Aug 21, 2018 at 8:45
1
C:Users{WindowsUser}AppDataLocalMicrosoftVisualStudio16.0_8183e7d1ComponentModelCache
Remove from this folder for VS 2019 ….
answered Aug 30, 2019 at 17:01
![]()
I am working on a Core 3 app and had this issue pop up when adding a controller. I figured out that the Microsoft.VisualStudio.Web.CodeGeneration.Design package was updated with a .net 4.x framework dll. Updating to the project to Core 3.1 fixed the issue.
answered Dec 18, 2019 at 20:11
HoodlumHoodlum
1,3931 gold badge11 silver badges23 bronze badges
just in case someone is interested — the solution with clean cache didnt work for me. but i’ve managed to solve an issue but uninstalling all .Net frameworks in the system and then install them back one by one.
answered Jun 15, 2017 at 14:51
LeonidLeonid
4765 silver badges15 bronze badges
I just restarted my visual studio and it worked.
answered Mar 21, 2018 at 18:00
KurkulaKurkula
6,29827 gold badges119 silver badges196 bronze badges
Try clearing the ComponentModelCache,
1.Close Visual Studio
2.Delete everything in this folder C:UsersAppDataLocalMicrosoftVisualStudio14.0ComponentModelCache
3.Restart Visual Studio
4.Check again
this also used VS2017 to get solution
answered May 28, 2018 at 20:04
![]()
I ran into a similar issue that prevented the code generation from working. Apparently, my metadata had unknown properties or values. I must admit I did not try all the answers here but who really wants to reinstall vs or download any of the numerous Nuget packages being used.
Cleaning the project worked for me (Build->Clean Solution) The generator was using some outdated binaries to build the controller and views. Cleaning the solution removed the outdated binaries and voilà.
answered Aug 28, 2018 at 21:56
user3416682user3416682
1132 silver badges8 bronze badges
I’m currently trying to familiarise myself with MVC 4. I’ve been developing with MVC 5 for a while, but I need to know MVC 4 to study for my MCSD certification. I’m following a tutorial via Pluralsight, targeting much older versions of Entity Framework, and MVC, (the video was released in 2013!)
I hit this exact same error 2 hours ago and have been tearing my hair out trying to figure out what is wrong. Thankfully, because the project in this tutorial is meaningless, I was able to step backward throughout the process to figure out what it was that was causing the object ref not set error, and fix it.
What I found was an error within the structure of my actual solution.
I had a MVC web project set up (‘ASP.NET Web Application (.NET Framework)‘), but I also had 2 class libraries, one holding my Data Access Layer, and one holding the domain setup for models connecting to my database.
These were both of type ‘Class Library (.NET Standard)‘.
The MVC project did not like this.
Once I created new projects of type ‘Class Library (.NET Framework)’, and copied all the files from the old libraries to the new ones and fixed the reference for the MVC web project, a rebuild and retry allowed me to scaffold the View correctly.
This may seem like an obvious fix, don’t put a .NET Standard project alongside a .NET Framework one and expect it to work normally, but it may help others fix this issue!
answered Aug 31, 2018 at 13:58
![]()
My problem was the Types used in the Model Class.
Using the Types like this:
[NotMapped]
[Display(Name = "Image")]
public HttpPostedFileBase ImageUpload { get; set; }
[NotMapped]
[Display(Name = "Valid from")]
public Nullable<DateTime> Valid { get; set; }
[NotMapped]
[Display(Name = "Expires")]
public Nullable<DateTime> Expires { get; set; }
No longer works in the Code Generator. I had to remove these types and scaffold without them, then add them later.
It is silly, [NotMapped] used to work when scaffolding.
Use the base Types: int, string, byte, and so on without Types like: DateTime, List, HttpPostedFileBase and so on.
answered Mar 19, 2019 at 20:55
![]()
Rusty NailRusty Nail
2,6283 gold badges32 silver badges54 bronze badges
I have been scratching my head with this one too, what i found in my instance was that an additional section had been added to my Web.config file. Commenting this out and rebuilding solved the issue and i was now able to add a new controller.
answered May 18, 2019 at 17:04
IcementholsIcementhols
6531 gold badge9 silver badges11 bronze badges
A simple VS restart worked for me. I just closed VS and restarted.
answered Sep 19, 2019 at 4:12
SajithdSajithd
5091 gold badge5 silver badges11 bronze badges
None of these solutions worked for me. I just updated Visual Studio (updates were available) and suddenly it just works.
answered Oct 16, 2019 at 2:58
![]()
Exel GamboaExel Gamboa
9361 gold badge14 silver badges25 bronze badges
The issue has been resolved after installed EntityFramework from nuget package manager into my project. Please take a look on your project references which already been added EntityFramework. Finally I can add the view with template after I added EntityFramework to project reference.
answered Oct 23, 2019 at 7:38
Deleting the .vs folder inside the solution directory worked for me.
answered Dec 16, 2019 at 16:54
Adam HeyAdam Hey
1,3961 gold badge19 silver badges22 bronze badges
I know this is a really old thread, but I came across it whilst working on my issue. Mine was caused because I had renamed one of my Model classes. Even though the app built and ran fine, when I tried to add a new controller I got the same error. For me, I just deleted the class I had renamed, added it back in and all was fine.
answered Jul 27, 2020 at 10:27
SkinnyPete63SkinnyPete63
5171 gold badge5 silver badges19 bronze badges
Check your Database Connection string and if there any syntax errors in the appsettings.json it will return this error.
answered Apr 23, 2021 at 5:46
![]()
TheepagTheepag
3032 silver badges15 bronze badges
Another common cause for this, which is hinted in the build log, is your IIS Express Web Server is running while you are trying to build a scaffold. Stop/Exit your web server and try building the scaffold again.
answered May 23, 2021 at 13:37
Dean PDean P
1,58318 silver badges22 bronze badges
Try unload and reload project (solution).
answered Apr 17, 2022 at 6:51
![]()
Dee NixDee Nix
1601 silver badge13 bronze badges
So, i had this problem in vs2019.
- none of the other suggestions helped me
This is what fixed me:
- upgrade .net 5.0 dependencies to 5.0.17

answered Sep 8, 2022 at 13:41
OmzigOmzig
8141 gold badge12 silver badges19 bronze badges
I had same error. what I did was to downgrade my Microsoft.VisualStudio.Web.CodeGeneration.Design to version 3.1.30 since my .net version was netcoreapp3.1. This means the problem was a mismatch of the versions.
So check your version of dotnet and get a matching version of Microsoft.VisualStudio.Web.CodeGeneration.Design that supports it.
answered Oct 25, 2022 at 9:10
![]()
1
I had similar proble to this one. I went through 2 appraches for solving this.
First Approach: Not The Best One…
I had created a project on VS2019, and tried to add a controller using VS2022. Not possible. I’d get an error every time.

Error ... Parameter name: searchFolder
Only from VS2019 I’d be able to scaffold the controller I needed. Not the best solution really… But it worked nevertheless.
You could try adding what you need from a different VS version.
Second Approach: The Best One
After further research I found this solution.
From Visual Studio Installer, I added the following components to my VS22 installation:

.NET Framework project and item templates
This made possible to add the controller I needed on VS22.
I know this solution does not point exactly to your problem, but it’s maybe a good lead to it. Like you, when I was trying to add/scaffold the controller, I was able to see all the components in the wizard, but in creation after naming it, the error was thrown.
answered Nov 30, 2022 at 15:11
![]()
carloswm85carloswm85
1,05410 silver badges20 bronze badges
I was also trying. I was facing face problem. I searched on google. I found an error solution. So I am sharing it with you.
- You should clear ComponentModelCache in your directory.
1 First Close Visual Studio
2 delete everything from this path
C:UsersAppDataLocalMicrosoftVisualStudio15.0ComponentModelCache
3 Visual Studio Start Again
Hopefully, error will finish
answered Jan 2 at 15:40
1
|
Volodya_ 14 / 12 / 3 Регистрация: 20.02.2018 Сообщений: 446 |
||||
|
1 |
||||
|
06.07.2021, 07:12. Показов 7650. Ответов 8 Метки asp .net core, c#, entity framework core, visual studio 2019, visual studio (Все метки)
Проект ASP NET CORE 3, использую EF Core 3.1.13. Ранее в этом же проекте контроллеры автоматически генерировались. Сейчас при попытке сгенерировать контроллер MVC с представлениями, использующий EF выдает ошибку: При запуске выбранного генератора кода произошла ошибка сбой при восстановлении пакета. откат изменений пакета для … Про гуглил данную ошибку и все пишут про отсутствия нужных пакетов и советуют через Nuget установить их. Пакеты, которые перечислялись у меня все в файле csproj есть:
Попробовал их удалить и снова переустановить, но это не решило проблему
__________________ 0 |
|
14 / 12 / 3 Регистрация: 20.02.2018 Сообщений: 446 |
|
|
07.07.2021, 15:24 [ТС] |
2 |
|
Создал новый проект, добавил в него через NuGet те же самые пакеты — все работает 0 |
|
14 / 12 / 3 Регистрация: 20.02.2018 Сообщений: 446 |
|
|
22.07.2021, 12:21 [ТС] |
3 |
|
Через некоторое время и в новом проекте перестало все работать 0 |
|
954 / 582 / 202 Регистрация: 08.08.2014 Сообщений: 1,844 |
|
|
22.07.2021, 15:08 |
4 |
|
Volodya_ Лечится просто — закрыть Студию, из sln-каталога удалить ‘.vs’-подкаталог, а из всех проектов удалить подкаталоги ‘bin’ и ‘obj’. Запустить Студию, пересобрать солюшен. 0 |
|
922 / 600 / 149 Регистрация: 09.09.2011 Сообщений: 1,879 Записей в блоге: 2 |
|
|
22.07.2021, 15:34 |
5 |
|
В 19-й Студии есть стабильный баг с версиями/доступностью пакетов из-за кривого кэширования в каталоге ‘.vs’. Отчасти правильно. .vs не нужно удалять. Там нет ничего связанного с пакетами и т.п. А вот кое-какие полезные настройки можно удалить. Лучший совет — bin и obj папки удалять. 0 |
|
954 / 582 / 202 Регистрация: 08.08.2014 Сообщений: 1,844 |
|
|
22.07.2021, 15:41 |
6 |
|
vs не нужно удалять Стабильно помогает именно удаление ‘.vs’, когда Студия упорно не видит новую версию пакета из нугета или не определяет новые пути подпроектов после реорганизации структуры проекта (перенос какого-нибудь из проектов в подкаталог). Не только на моей машине. Апдейты все установлены. 0 |
|
14 / 12 / 3 Регистрация: 20.02.2018 Сообщений: 446 |
|
|
22.07.2021, 21:56 [ТС] |
7 |
|
В 19-й Студии есть стабильный баг с версиями/доступностью пакетов из-за кривого кэширования в каталоге ‘.vs’. Вышел из проекта, закрыл VS, удалил .vs’-подкаталог, удалил подкаталоги ‘bin’ и ‘obj’, удалил ещё до кучи и .sln-файл, запустил VS она сразу автоматически создала подкаталоги ‘bin’ и ‘obj’, пересобрал решение — таже ошибка. Наличие git как-то может повлиять? Добавлено через 4 часа 16 минут 0 |
|
922 / 600 / 149 Регистрация: 09.09.2011 Сообщений: 1,879 Записей в блоге: 2 |
|
|
23.07.2021, 08:29 |
8 |
|
Пытаюсь создать снова новый проект и в нем сгенерировать, но он уже и в новом проекте такую же ошибку выдает Это проблема индивидуально для вашего проекта, который мы даже не видели. А я например вообще без понятия как работает этот генератор. Нужен ли он в референцах, какой и как и когда генерируются контроллеры. 0 |
|
14 / 12 / 3 Регистрация: 20.02.2018 Сообщений: 446 |
|
|
23.07.2021, 13:16 [ТС] |
9 |
|
Это проблема индивидуально для вашего проекта, который мы даже не видели. А я например вообще без понятия как работает этот генератор. Нужен ли он в референцах, какой и как и когда генерируются контроллеры. Логов нет, я же проект не запускаю. Этот генератор генерирует шаблон контроллера на основании созданной сущности. Поэтому кроме вылетающего сообщения ничего нет. Или все-таки где-то что-то ещё есть? Где смотреть нужно? 0 |
I am having a problem following the tutorial exactly as written. When I try to add a Razor page as instructed…
Complete the Add Razor Pages using Entity Framework (CRUD) dialog:
In the Model class drop down, select Movie (RazorPagesMovie.Models).
In the Data context class row, select the + (plus) sign and accept the generated name RazorPagesMovie.Models.RazorPagesMovieContext.
In the Data context class drop down, select RazorPagesMovie.Models.RazorPagesMovieContext
Select Add.
I get an error that says… ‘There was an error running the selected code generator: The entity type ‘Program’ requires a primary key to be defined.’
I am using Microsoft Visual Studio Community 2017. Version 15.8.5
Document Details
⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.
- ID: 6719f08e-3bd7-dc1a-71df-f2ef9fbca9d8
- Version Independent ID: 7096fdb3-612e-9e00-bd0b-8ea4886a09ce
- Content: Add a model to a Razor Pages app in ASP.NET Core
- Content Source: aspnetcore/tutorials/razor-pages/model.md
- Product: aspnet-core
- GitHub Login: @Rick-Anderson
- Microsoft Alias: riande
I am having a problem following the tutorial exactly as written. When I try to add a Razor page as instructed…
Complete the Add Razor Pages using Entity Framework (CRUD) dialog:
In the Model class drop down, select Movie (RazorPagesMovie.Models).
In the Data context class row, select the + (plus) sign and accept the generated name RazorPagesMovie.Models.RazorPagesMovieContext.
In the Data context class drop down, select RazorPagesMovie.Models.RazorPagesMovieContext
Select Add.
I get an error that says… ‘There was an error running the selected code generator: The entity type ‘Program’ requires a primary key to be defined.’
I am using Microsoft Visual Studio Community 2017. Version 15.8.5
Document Details
⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.
- ID: 6719f08e-3bd7-dc1a-71df-f2ef9fbca9d8
- Version Independent ID: 7096fdb3-612e-9e00-bd0b-8ea4886a09ce
- Content: Add a model to a Razor Pages app in ASP.NET Core
- Content Source: aspnetcore/tutorials/razor-pages/model.md
- Product: aspnet-core
- GitHub Login: @Rick-Anderson
- Microsoft Alias: riande
Произошла ошибка при запуске выбранного генератора кода: «Ссылка на объект не установлена для экземпляра объекта». Ошибка?

Я испробовал все решения, такие как ремонт VS 2013, но бесполезно. Когда вы создаете контроллер, щелкая правой кнопкой мыши на папке Controller и добавляете контроллер, затем вы щелкаете правой кнопкой мыши в Action недавно созданного контроллера и выбираете Add View, это происходит именно тогда, когда я пытаюсь создать представление. Это не новый проект, это существующий проект.
24 авг. 2016, в 17:24
Поделиться
Источник
У меня такая же ошибка, я просто удалил только разрешение на чтение в папке, где находится веб-проект
Ricardo Silva
13 март 2018, в 17:47
Поделиться
Для меня ошибка связана с тем, что у меня был проект в моем решении, который был библиотекой проектов .NET Core и упоминался в проекте, в котором размещался DbContext.
Удаление — или, я думаю, изменение типа — в основной библиотеке .NET была устранена проблема
Timo Hermans
11 июнь 2017, в 14:05
Поделиться
У меня была эта проблема на моем VS2017, и я решил ее, выполнив это:
Перейдите в C:UsersusernameAppDataLocalMicrosoftVisualStudio15.0_7fca0c70 и вы увидите папку с именем ComponentModelCache только что переименованную в _ComponentModelCache или что-то еще, Visual Studio снова создаст эту папку.
Под именем папки VisualStudio 15.0_7fca0c70 можно заметить, что это зависит от версии VS. Теперь вы готовы идти. Надеюсь, это кому-нибудь поможет.
Mohit Lohani
10 апр. 2019, в 07:04
Поделиться
Просто измените вашу ConnectionString в файле Web.Config От
<add name="xxx" connectionString="Data Source=xxx;initial catalog=xxx;Persist Security Info=True;User ID=xxxx;Password=xxxx;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
к
<add name="xxx" connectionString="metadata=res://*/EFMOdel.csdl|res://*/EFMOdel.ssdl|res://*/EFMOdel.msl;provider=System.Data.SqlClient;provider connection string="data source=xxxx;initial catalog=xxxx;persist security info=True;user id=xxxx;password=xxx;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
ghanshyam shah
23 окт. 2018, в 01:00
Поделиться
Устранил ошибку, запустив целый новый проект, потому что я изначально ссылался на библиотеку классов, в которой размещался код доступа к данным и бизнес-логики для моего проекта.
Amantle Mashele
25 сен. 2018, в 10:07
Поделиться
Или, может быть, как я, вы не заметили, что поле «Класс контекста данных» было пустым. К сожалению. Если это так, просто выберите свой класс контекста данных и повторите попытку.
Там действительно должно быть лучше ошибка для этого сценария.
Opsimath
18 май 2018, в 18:28
Поделиться
Эта ошибка связана с моделью данных платформы Entity.
для решения Выполнение этих шагов…
- Удалите модель данных Entity Framework.
- Снова регенерировать модель из проекта базы данных.
- затем переделайте решение… и наслаждайтесь кодированием.
Umer Ashiq
19 апр. 2017, в 12:46
Поделиться
У меня такая же ошибка в vs2017 на windows10, пожалуйста, попробуйте запустить vs от имени администратора, надеюсь, это будет работать и для вас.
Frank
19 апр. 2019, в 03:28
Поделиться
Перезапустите Visual Studio и попробуйте снова.
Shadi Namrouti
14 апр. 2019, в 15:01
Поделиться
Ещё вопросы
- 0Перезагрузите вкладки в angularjs
- 1Android: создание обработчика в TimerTask внутри службы
- 1Восстановление базы данных SQL Server из снимка в C #
- 1Объедините два нажатия кнопки селена в if if
- 1RadioButtonList Выбор конкретного индекса
- 0jQuery append — html wrote не вызывает другие события
- 0JavaScript с использованием DOM и изменение цвета
- 0Как выбрать строки, которые имеют все значения в коллекции идентификаторов
- 0Сохранение состояния меню после перезагрузки страницы
- 1Невозможно привести .SelectedItems из выпуска DataGrid
- 0ошибка: переопределение класса TextDocsCmpr
- 0jQuery всплывающая ошибка для подписки на комментарии
- 0Установить значение по умолчанию выбрать базу данных формы AngularJS
- 1Воспроизведение кодированного пользовательского интерфейса из консольного проекта при воспроизведении. Функция Initialize () вызывает исключение System.TypeInitialization.
- 1Как использовать изображение в ListView из базы данных в Android?
- 0Angularjs — ошибка: $ location и $ anchorScroll для прокрутки вызова 2 раза на мой контроллер
- 1Как заставить класс использовать метод получения / установки по умолчанию, когда на него ссылаются непосредственно в C #?
- 0Общая архитектура InterlockedIncrement для 32/64-битных
- 0Как вставить значение эха в переменную? [Дубликат]
- 0Дескрипторы для Pointclouds
- 1Добавление слушателей в Netbeans
- 0QTableView, выберите и Shift + клик
- 1Наследование объектов в protobuf-сети
- 0Граф с Join в MySQL
- 0.query () отображает неверный путь
- 0я должен установить все базы данных charset utf8_general_ci
- 1Отсутствует @using при просмотре бритвы
- 0Разбор строки массива массива строк обратно в массив
- 1Улучшение производительности вложенного цикла for в node.js
- 1VueJs — DOM не обновляется при мутации массива
- 0Как обновить HTML-контент, когда я выполняю процесс в предложении, в то время как с JavaScript
- 1Хэшированное значение регулярное выражение
- 0Как разрешить внешний символ
- 0jQuery Mobile настройки Иконки для кнопок
- 0Как загрузить и вставить несколько изображений в PHP?
- 0Угловая нг-сетка отключает автоматическую генерацию столбцов
- 0C # взаимодействие с CUDA C dll — избыточный
- 1Разбор пустого тега с ElementTree
- 1Прочитайте zip-файлы из amazon s3, используя boto3 и python
- 1Правильный способ сократить код с помощью множества приведений и очевидных шаблонов в C #
- 0JQuery не работает должным образом на mouseenter и mouseleave
- 0Как использовать форматтер / парсеры директивы ngModel в пользовательской директиве?
- 0Ошибка запроса данных PHP с объектом / строкой, теперь конструкция SQLite3
- 0Создайте триггер ежегодно в MySQL
- 0Найти точный дубликат по полю таблицы соединений
- 1Selenium webdriver element.click () не работает должным образом (chrome, mocha)
- 1Является ли RCW (Runtime Callable Wrapper) единственным способом вызова неуправляемого com-объекта в .net?
- 0Войти и оплатить с помощью интеграции с Amazon
- 1Как я могу использовать плагин ServiceStack RegistrationFeature с Redis?
- 1использовать список объектов из формы один в форме два
|
Volodya_ 14 / 12 / 3 Регистрация: 20.02.2018 Сообщений: 446 |
||||
|
1 |
||||
|
06.07.2021, 07:12. Показов 9442. Ответов 8 Метки asp .net core, c#, entity framework core, visual studio 2019, visual studio (Все метки)
Проект ASP NET CORE 3, использую EF Core 3.1.13. Ранее в этом же проекте контроллеры автоматически генерировались. Сейчас при попытке сгенерировать контроллер MVC с представлениями, использующий EF выдает ошибку: При запуске выбранного генератора кода произошла ошибка сбой при восстановлении пакета. откат изменений пакета для … Про гуглил данную ошибку и все пишут про отсутствия нужных пакетов и советуют через Nuget установить их. Пакеты, которые перечислялись у меня все в файле csproj есть:
Попробовал их удалить и снова переустановить, но это не решило проблему
0 |
|
14 / 12 / 3 Регистрация: 20.02.2018 Сообщений: 446 |
|
|
07.07.2021, 15:24 [ТС] |
2 |
|
Создал новый проект, добавил в него через NuGet те же самые пакеты — все работает
0 |
|
14 / 12 / 3 Регистрация: 20.02.2018 Сообщений: 446 |
|
|
22.07.2021, 12:21 [ТС] |
3 |
|
Через некоторое время и в новом проекте перестало все работать
0 |
|
1009 / 627 / 213 Регистрация: 08.08.2014 Сообщений: 1,950 |
|
|
22.07.2021, 15:08 |
4 |
|
Volodya_ Лечится просто — закрыть Студию, из sln-каталога удалить ‘.vs’-подкаталог, а из всех проектов удалить подкаталоги ‘bin’ и ‘obj’. Запустить Студию, пересобрать солюшен.
0 |
|
979 / 645 / 161 Регистрация: 09.09.2011 Сообщений: 1,960 Записей в блоге: 2 |
|
|
22.07.2021, 15:34 |
5 |
|
В 19-й Студии есть стабильный баг с версиями/доступностью пакетов из-за кривого кэширования в каталоге ‘.vs’. Отчасти правильно. .vs не нужно удалять. Там нет ничего связанного с пакетами и т.п. А вот кое-какие полезные настройки можно удалить. Лучший совет — bin и obj папки удалять.
0 |
|
1009 / 627 / 213 Регистрация: 08.08.2014 Сообщений: 1,950 |
|
|
22.07.2021, 15:41 |
6 |
|
vs не нужно удалять Стабильно помогает именно удаление ‘.vs’, когда Студия упорно не видит новую версию пакета из нугета или не определяет новые пути подпроектов после реорганизации структуры проекта (перенос какого-нибудь из проектов в подкаталог). Не только на моей машине. Апдейты все установлены.
0 |
|
14 / 12 / 3 Регистрация: 20.02.2018 Сообщений: 446 |
|
|
22.07.2021, 21:56 [ТС] |
7 |
|
В 19-й Студии есть стабильный баг с версиями/доступностью пакетов из-за кривого кэширования в каталоге ‘.vs’. Вышел из проекта, закрыл VS, удалил .vs’-подкаталог, удалил подкаталоги ‘bin’ и ‘obj’, удалил ещё до кучи и .sln-файл, запустил VS она сразу автоматически создала подкаталоги ‘bin’ и ‘obj’, пересобрал решение — таже ошибка. Наличие git как-то может повлиять? Добавлено через 4 часа 16 минут
0 |
|
979 / 645 / 161 Регистрация: 09.09.2011 Сообщений: 1,960 Записей в блоге: 2 |
|
|
23.07.2021, 08:29 |
8 |
|
Пытаюсь создать снова новый проект и в нем сгенерировать, но он уже и в новом проекте такую же ошибку выдает Это проблема индивидуально для вашего проекта, который мы даже не видели. А я например вообще без понятия как работает этот генератор. Нужен ли он в референцах, какой и как и когда генерируются контроллеры.
0 |
|
14 / 12 / 3 Регистрация: 20.02.2018 Сообщений: 446 |
|
|
23.07.2021, 13:16 [ТС] |
9 |
|
Это проблема индивидуально для вашего проекта, который мы даже не видели. А я например вообще без понятия как работает этот генератор. Нужен ли он в референцах, какой и как и когда генерируются контроллеры. Логов нет, я же проект не запускаю. Этот генератор генерирует шаблон контроллера на основании созданной сущности. Поэтому кроме вылетающего сообщения ничего нет. Или все-таки где-то что-то ещё есть? Где смотреть нужно?
0 |


