При запуске выбранного генератора кода произошла ошибка mvc

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:UsersXXXXXXXAppDataL...

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.

Community's user avatar

asked Nov 12, 2013 at 4:25

Brian Webb's user avatar

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's user avatar

Liam

26.8k27 gold badges120 silver badges185 bronze badges

answered Aug 16, 2014 at 22:31

Bill B's user avatar

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.

  1. Possibly the nuget package has a flaw
  2. 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.

Raphaël Colantonio's user avatar

answered Jan 22, 2014 at 1:55

Brian Webb's user avatar

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

isingh's user avatar

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:

  1. Open your working folder on your hard drive for your solution.
  2. Delete everything inside the BIN folder
  3. Delete everything inside the OBJ folder
  4. Clean Solution, Rebuild Solution, Add Controller via scaffolding

Voila! (for me)

answered May 13, 2015 at 14:46

erikrunia's user avatar

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:

  1. For each project in solution Project->Properties->Application: Set Target Framework to .Net 4.5 (or whatever you need).
  2. 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.
  3. Clean and Rebuild Solution.

Jess's user avatar

Jess

23k19 gold badges122 silver badges141 bronze badges

answered May 1, 2014 at 12:52

RitchieD's user avatar

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 Dhaou's user avatar

Moslem Ben DhaouMoslem Ben Dhaou

6,8577 gold badges62 silver badges93 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; }

Community's user avatar

answered Nov 14, 2014 at 9:33

scyu's user avatar

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 Pretorius's user avatar

Gerrie PretoriusGerrie Pretorius

3,1512 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

Jim Taliadoros's user avatar

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:

  1. Go to your project and update all NuGet packages to latest version.
  2. Build your application till Build success.
  3. Close solution and reopen same.
  4. And try to add file like controller, class, etc.

error picture

TylerH's user avatar

TylerH

20.5k62 gold badges75 silver badges97 bronze badges

answered Aug 2, 2019 at 8:06

Manjunath K's user avatar

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

Lindsey's user avatar

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.

  1. First, switch to Debug|x86—use Solution (right-click) Configuration Manager for all the projects in your solution. (Debug|Any CPU may also work).
  2. Clean your solution.
  3. Shut down Visual Studio. (cannot get it to work if I skip this).
  4. Open Visual Studio.
  5. Open your solution.
  6. Build your solution.
  7. 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

DWright's user avatar

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 Oschler's user avatar

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's user avatar

bummi

27k13 gold badges62 silver badges101 bronze badges

answered Dec 12, 2016 at 20:00

Marko's user avatar

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:

  1. Comment out modelBuilder in your Context class.
  2. Clean Solution, Rebuild Solution.
  3. Add view and Controller via scaffolding
  4. Uncomment modelbuilder.

TylerH's user avatar

TylerH

20.5k62 gold badges75 silver badges97 bronze badges

answered May 15, 2016 at 10:22

freddy's user avatar

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 Marshall's user avatar

Adam MarshallAdam Marshall

2,9018 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 S's user avatar

John SJohn S

7,77121 gold badges75 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

jmcm's user avatar

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.Mackey's user avatar

P.Brian.MackeyP.Brian.Mackey

42.7k65 gold badges232 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

gummylick's user avatar

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

Iwona Kubowicz's user avatar

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's user avatar

TylerH

20.5k62 gold badges75 silver badges97 bronze badges

answered Jan 8, 2020 at 19:01

Hugo Nava Kopp's user avatar

Hugo Nava KoppHugo Nava Kopp

2,7972 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

simon9k's user avatar

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

billw's user avatar

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

shashi kumar's user avatar

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.

Community's user avatar

asked Nov 12, 2013 at 4:25

Brian Webb's user avatar

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's user avatar

Liam

26.8k27 gold badges120 silver badges185 bronze badges

answered Aug 16, 2014 at 22:31

Bill B's user avatar

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.

  1. Possibly the nuget package has a flaw
  2. 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.

Raphaël Colantonio's user avatar

answered Jan 22, 2014 at 1:55

Brian Webb's user avatar

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

isingh's user avatar

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:

  1. Open your working folder on your hard drive for your solution.
  2. Delete everything inside the BIN folder
  3. Delete everything inside the OBJ folder
  4. Clean Solution, Rebuild Solution, Add Controller via scaffolding

Voila! (for me)

answered May 13, 2015 at 14:46

erikrunia's user avatar

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:

  1. For each project in solution Project->Properties->Application: Set Target Framework to .Net 4.5 (or whatever you need).
  2. 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.
  3. Clean and Rebuild Solution.

Jess's user avatar

Jess

23k19 gold badges122 silver badges141 bronze badges

answered May 1, 2014 at 12:52

RitchieD's user avatar

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 Dhaou's user avatar

Moslem Ben DhaouMoslem Ben Dhaou

6,8577 gold badges62 silver badges93 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; }

Community's user avatar

answered Nov 14, 2014 at 9:33

scyu's user avatar

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 Pretorius's user avatar

Gerrie PretoriusGerrie Pretorius

3,1512 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

Jim Taliadoros's user avatar

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:

  1. Go to your project and update all NuGet packages to latest version.
  2. Build your application till Build success.
  3. Close solution and reopen same.
  4. And try to add file like controller, class, etc.

error picture

TylerH's user avatar

TylerH

20.5k62 gold badges75 silver badges97 bronze badges

answered Aug 2, 2019 at 8:06

Manjunath K's user avatar

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

Lindsey's user avatar

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.

  1. First, switch to Debug|x86—use Solution (right-click) Configuration Manager for all the projects in your solution. (Debug|Any CPU may also work).
  2. Clean your solution.
  3. Shut down Visual Studio. (cannot get it to work if I skip this).
  4. Open Visual Studio.
  5. Open your solution.
  6. Build your solution.
  7. 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

DWright's user avatar

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 Oschler's user avatar

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's user avatar

bummi

27k13 gold badges62 silver badges101 bronze badges

answered Dec 12, 2016 at 20:00

Marko's user avatar

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:

  1. Comment out modelBuilder in your Context class.
  2. Clean Solution, Rebuild Solution.
  3. Add view and Controller via scaffolding
  4. Uncomment modelbuilder.

TylerH's user avatar

TylerH

20.5k62 gold badges75 silver badges97 bronze badges

answered May 15, 2016 at 10:22

freddy's user avatar

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 Marshall's user avatar

Adam MarshallAdam Marshall

2,9018 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 S's user avatar

John SJohn S

7,77121 gold badges75 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

jmcm's user avatar

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.Mackey's user avatar

P.Brian.MackeyP.Brian.Mackey

42.7k65 gold badges232 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

gummylick's user avatar

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

Iwona Kubowicz's user avatar

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's user avatar

TylerH

20.5k62 gold badges75 silver badges97 bronze badges

answered Jan 8, 2020 at 19:01

Hugo Nava Kopp's user avatar

Hugo Nava KoppHugo Nava Kopp

2,7972 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

simon9k's user avatar

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

billw's user avatar

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

shashi kumar's user avatar

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 :

enter image description here

Chosen Empty Template with MVC checked :

enter image description here

Tried to Add View from a Controller :

enter image description here

Some settings …

enter image description here

The Error :

enter image description here

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

AymenDaoudi's user avatar

AymenDaoudiAymenDaoudi

7,5119 gold badges52 silver badges83 bronze badges

2

Try clearing the ComponentModelCache, the cache will rebuild next time VS is launched.

  1. Close Visual Studio
  2. Delete everything in this folder C:Users [your users name] AppDataLocalMicrosoftVisualStudio14.0ComponentModelCache
  3. Restart Visual Studio

14.0 is for visual studio 2015. This will work for other versions also.

VSB's user avatar

VSB

9,46916 gold badges69 silver badges137 bronze badges

answered Mar 5, 2016 at 14:06

longday's user avatar

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.expert's user avatar

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 Labutin's user avatar

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.
  • 8) 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's user avatar

dorukayhan

1,5054 gold badges23 silver badges27 bronze badges

answered Jul 27, 2016 at 17:17

sh.alawneh's user avatar

sh.alawnehsh.alawneh

6195 silver badges13 bronze badges

1

In my case helped the following:

  1. Restart VS
  2. Solution Explorer => Right click on solution => Rebuild solution

answered Nov 29, 2020 at 17:33

essential's user avatar

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

enter image description here

and the code generation package with version 5.0.2

enter image description here

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

Nour's user avatar

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

Mohammad omar's user avatar

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

sGermosen's user avatar

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

Oleksandr Kyselov's user avatar

1

C:Users{WindowsUser}AppDataLocalMicrosoftVisualStudio16.0_8183e7d1ComponentModelCache

Remove from this folder for VS 2019 ….

answered Aug 30, 2019 at 17:01

Farzad Sepehr's user avatar

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

Hoodlum's user avatar

HoodlumHoodlum

1,4031 gold badge12 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

Leonid's user avatar

LeonidLeonid

4765 silver badges15 bronze badges

I just restarted my visual studio and it worked.

answered Mar 21, 2018 at 18:00

Kurkula's user avatar

KurkulaKurkula

6,32827 gold badges119 silver badges197 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

Deepak Savani's user avatar

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

user3416682's user avatar

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

IfElseTryCatch's user avatar

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 Nail's user avatar

Rusty NailRusty Nail

2,6343 gold badges33 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

Icementhols's user avatar

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

Sajithd's user avatar

SajithdSajithd

5191 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 Gamboa's user avatar

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

Ei Ei Phyu's user avatar

Deleting the .vs folder inside the solution directory worked for me.

answered Dec 16, 2019 at 16:54

Adam Hey's user avatar

Adam HeyAdam Hey

1,4161 gold badge20 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

SkinnyPete63's user avatar

SkinnyPete63SkinnyPete63

5391 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

Theepag's user avatar

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 P's user avatar

Dean PDean P

1,62318 silver badges22 bronze badges

Try unload and reload project (solution).

answered Apr 17, 2022 at 6:51

Dee Nix's user avatar

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

enter image description here

answered Sep 8, 2022 at 13:41

Omzig's user avatar

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

Daniel Akudbilla's user avatar

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.

searchFolders

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

.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

carloswm85's user avatar

carloswm85carloswm85

1,06510 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

Abrar ul Hassan's user avatar

1

Volodya_

14 / 12 / 3

Регистрация: 20.02.2018

Сообщений: 446

1

06.07.2021, 07:12. Показов 7886. Ответов 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 есть:

C#
1
2
3
4
5
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration" Version="3.1.5" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.5" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Utils" Version="3.1.5" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGenerators.Mvc" Version="3.1.5" />
    <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="3.2.4" />

Попробовал их удалить и снова переустановить, но это не решило проблему

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



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



966 / 592 / 204

Регистрация: 08.08.2014

Сообщений: 1,862

22.07.2021, 15:08

4

Volodya_
В 19-й Студии есть стабильный баг с версиями/доступностью пакетов из-за кривого кэширования в каталоге ‘.vs’.

Лечится просто — закрыть Студию, из sln-каталога удалить ‘.vs’-подкаталог, а из всех проектов удалить подкаталоги ‘bin’ и ‘obj’. Запустить Студию, пересобрать солюшен.



0



923 / 600 / 150

Регистрация: 09.09.2011

Сообщений: 1,881

Записей в блоге: 2

22.07.2021, 15:34

5

Цитата
Сообщение от kotelok
Посмотреть сообщение

В 19-й Студии есть стабильный баг с версиями/доступностью пакетов из-за кривого кэширования в каталоге ‘.vs’.
Лечится просто — закрыть Студию, из sln-каталога удалить ‘.vs’-подкаталог, а из всех проектов удалить подкаталоги ‘bin’ и ‘obj’. Запустить Студию, пересобрать солюшен.

Отчасти правильно.

.vs не нужно удалять. Там нет ничего связанного с пакетами и т.п. А вот кое-какие полезные настройки можно удалить.

Лучший совет — bin и obj папки удалять.
Но по своему опыту могу точно сказать — что удалять их приходится только если я, например, в текущем каталоге ветку переключил в которой не было изменений, в том числе зависимостями. Тогда надо обязательно сборку перебильживать в чистую. В остальных случаях это бесполезно.



0



966 / 592 / 204

Регистрация: 08.08.2014

Сообщений: 1,862

22.07.2021, 15:41

6

Цитата
Сообщение от HF
Посмотреть сообщение

vs не нужно удалять

Стабильно помогает именно удаление ‘.vs’, когда Студия упорно не видит новую версию пакета из нугета или не определяет новые пути подпроектов после реорганизации структуры проекта (перенос какого-нибудь из проектов в подкаталог). Не только на моей машине. Апдейты все установлены.



0



14 / 12 / 3

Регистрация: 20.02.2018

Сообщений: 446

22.07.2021, 21:56

 [ТС]

7

Цитата
Сообщение от kotelok
Посмотреть сообщение

В 19-й Студии есть стабильный баг с версиями/доступностью пакетов из-за кривого кэширования в каталоге ‘.vs’.
Лечится просто — закрыть Студию, из sln-каталога удалить ‘.vs’-подкаталог, а из всех проектов удалить подкаталоги ‘bin’ и ‘obj’. Запустить Студию, пересобрать солюшен.

Вышел из проекта, закрыл VS, удалил .vs’-подкаталог, удалил подкаталоги ‘bin’ и ‘obj’, удалил ещё до кучи и .sln-файл, запустил VS она сразу автоматически создала подкаталоги ‘bin’ и ‘obj’, пересобрал решение — таже ошибка.

Наличие git как-то может повлиять?

Добавлено через 4 часа 16 минут
Пытаюсь создать снова новый проект и в нем сгенерировать, но он уже и в новом проекте такую же ошибку выдает



0



923 / 600 / 150

Регистрация: 09.09.2011

Сообщений: 1,881

Записей в блоге: 2

23.07.2021, 08:29

8

Цитата
Сообщение от Volodya_
Посмотреть сообщение

Пытаюсь создать снова новый проект и в нем сгенерировать, но он уже и в новом проекте такую же ошибку выдает

Это проблема индивидуально для вашего проекта, который мы даже не видели. А я например вообще без понятия как работает этот генератор. Нужен ли он в референцах, какой и как и когда генерируются контроллеры.
Указанная вами ошибка обычно связана с зависимостями, которые не совместимы или для проекта вообще или для других пакетов. Может быть тот же ЕФ не совместим с этой версией. Если например убрать эти ссылки, то наверняка будут ошибки типа «Пакет ХХХ ожидал и не нашёл зависимость НННН версии ЮЮЮЮ»
Для начала прочитай полный лог билда. Если не достаточно там информации — увеличьте уровень логирования. В итоге найдёте информацию о конфликтах и попытках исправить или рекомендациях.



0



14 / 12 / 3

Регистрация: 20.02.2018

Сообщений: 446

23.07.2021, 13:16

 [ТС]

9

Цитата
Сообщение от HF
Посмотреть сообщение

Это проблема индивидуально для вашего проекта, который мы даже не видели. А я например вообще без понятия как работает этот генератор. Нужен ли он в референцах, какой и как и когда генерируются контроллеры.
Указанная вами ошибка обычно связана с зависимостями, которые не совместимы или для проекта вообще или для других пакетов. Может быть тот же ЕФ не совместим с этой версией. Если например убрать эти ссылки, то наверняка будут ошибки типа «Пакет ХХХ ожидал и не нашёл зависимость НННН версии ЮЮЮЮ»
Для начала прочитай полный лог билда. Если не достаточно там информации — увеличьте уровень логирования. В итоге найдёте информацию о конфликтах и попытках исправить или рекомендациях.

Логов нет, я же проект не запускаю. Этот генератор генерирует шаблон контроллера на основании созданной сущности. Поэтому кроме вылетающего сообщения ничего нет. Или все-таки где-то что-то ещё есть? Где смотреть нужно?



0



Как самостоятельно исправить код ошибки 0x00000000 в операционной системе Windows?

0x00000000 — эта ошибка может возникнуть при запуске программ, игр, приложений. Возникновение происходит, когда запущенное приложение пытается получить доступ к закрытому участку памяти, а специальная функция DEP встроенная Windows блокирует его.

Варианты отображения сообщения

На экране пользователь может увидеть такую информацию: «Инструкция по адресу 0x000…. обратилась к …… Память не может быть read». В окне ошибки будет предложено два варианта решения: завершение приложения или его отладка.
Также вариант проблемы может выглядеть так: «Инструкция по адресу 0x000…. обратилась к …… Память не может быть written». В этом варианте будет предложен аналогичный способ решения.
В случае появления проблем при запуске игр, сообщение может выглядеть так:

Оба варианта сообщения означают, что программа собиралась использовать доступ к закрытой памяти, но функция дала отказ, поэтому появился данный код ошибки. Чаще всего данная проблема встречается при использовании программы virtualbox, которая создает виртуализацию системы. Она пытается получить доступ к закрытым участкам памяти и блокируется функцией Windows.
Решить эту проблему можно несколькими вариантами, и подходят эти решения для всех версий Виндовс — 7, 8, 10.

Как ее исправить?

Способ №1

Данный способ является Универсальным для всех версий Windows и достаточно простым:

Во вкладке существует два варианта работы DEP. Нам необходим второй вариант — включить DEP для всех программ и служб, кроме выбранных ниже. Теперь необходимо выбрать кнопку добавить и выбрать необходимые приложения которые будут находиться в списке исключений. Такие программы и будут работать без возникновения ошибки.

Способ №2

Второй способ — это Проверка компьютера на антивирусы или полное отключения DEP.

Для начала следует обновить ваш антивирус до самой последней версии и провести полное сканирование пк. После чего можно попробовать в ручном режиме отключить функцию DEP:

Предотвращение выполнения данных — DEP — это в своем роде защитная функция Windows, которая стабилизирует работу компьютера. Поэтому отключение может вести к некорректной работе ПК, но если вовремя обновлять антивирус и хотя бы 2 раза в неделю проверять компьютер, то этого будет достаточно для стабильной работы и отсутствия подобных проблем.

Полезное видео

Наглядный процесс решения данной проблемы с программой Virtual Box вы можете посмотреть здесь:

Все ошибки в Genshin Impact

Ошибки в Genshin Impact будут появляться у некоторых игроков вне зависимости от платформы, на которой они будут играть. Мы предлагаем вам рассмотреть основные ошибки, с которыми вы можете столкнуться на самых разных этапах игры.

Ошибка 0xc0000005 Genshin Impact

Ошибка 0xc0000005 в Genshin Impact связана с тем, что во время загрузки лаунчер потерял путь к скачиванию. Для того, чтобы такая проблема больше не возникала, необходимо сделать следующее:

После того, как вы выполнили все эти действия, Ошибка 0xc0000005 в Genshin Impact не будет вас больше беспокоить.

Ошибка 12 4301 Геншин

Ошибка 12 4301 в Геншин возникает тогда, когда вы пытаетесь загрузить игровые данные. Для того, чтобы избежать ее мы рекомендуем:

В том случае, если у вас все равно возникает ошибка 12 4301 в Genshin Impact, мы рекомендуем удалить и заново переустановить лаунчер и игру.

Ошибка 9114 в Genshin Impact

Ошибка 9114 в Genshin Impact исправляется несколькими способами:

Ошибка 9910 Геншин Импакт

В Геншин Импакт ошибка 9910 может возникнуть из-за проблем с загрузкой ресурсов или других игровых файлов. Мы рекомендуем вам:

Ошибка 9101 в Genshin Impact

Ошибка 9101 в Genshin Imapact также связана с загрузкой ресурсов и файлов игры. Поэтому мы рекомендуем вам загрузить игру вручную, но, перед этим, обновить загрузчик:

Ошибка 9908 в Genshin Impact

Ошибка 9908 в Genshin Impact возникает при попытке загрузить ресурсы и файлы игры. Ее наличие говорит о том, что целостность игры была нарушена. Мы предлагаем вам сделать следующее:

Ошибка 9004 Геншин Импакт

Ошибка 9004 в Геншин Импакт возникнет при попытке загрузить ресурсы и файлы игры, из-за которых целостность была нарушена. Для того, чтобы решить эту проблему вы можете сделать следующее:

Ошибка 9203 в Genshin Impact

Ошибка 9203 в Genshin Impact сигнализирует о том, что у вас не загрузили ресурсы игры. Причиной этому может послужить сбой интернет-подключения во время загрузки файлов игры или же просто конфликт некоторых файлов между собой. Сделайте следующее:

Если вам это не помогло, то рекомендуем удалить и заново переустановить загрузчик и саму игру.

Ошибка 4206 Геншин Импакт

В Геншин Импакт ошибка 4206 будет сопровождать вас в том случае, если у вас возникли проблемы с загрузкой файлов игры и вы не можете загрузить свой аккаунт. мы рекомендуем, в первую очередь:

Ошибка 1 4308 в Genshin Impact

Ошибка 1 4308 в Genshin Impact может быть вызвана сбоями в загрузке файлов и подключении к вашему аккаунту. Для того, чтобы проверить в чем ваша проблема и решить ее, мы рекомендуем:

Ошибка 0xc000007b в Геншин Импакт

Ошибка 0xc000007b в Геншин Импакт возникает как правило при запуске приложения. Для того, чтобы ее решить, нужно сделать следующее:

Ошибка при запуске приложения 0xc000007b Геншин Импакт может быть также решена при помощи техподдержки. Но туда стоит обращаться в том случае, если вы уже попробовали вышеперечисленные способы и они оказались бесполезны. В заявке обязательно укажите, что вы опробовали несколько вариантов, но они не привели к успеху.

Ошибка аккаунта или пароля в Genshin Impact

Ошибка аккаунта или пароля Genshin Impact может возникнуть при попытке восстановить доступ к аккаунту или же при попытке зайти в него. Вне зависимости от этого, единственным рабочим вариантом является восстановление пароля через номер вашего телефона (если вы его привязали) или почту.

Для этого достаточно нажать на «Забыли пароль?» и продолжить следовать инструкциям.

Но перед тем, как использовать этот вариант, убедитесь, что вы действительно ввели правильные данные. Ведь ошибка аккаунта или пароля Геншин Импакт может возникать, в том числе, и тогда, когда вы используете капс или же кириллицу.

Произошла ошибка загрузки ресурсов Genshin Impact

Многие игроки сталкиваются с проблемой, при которой произошла ошибка загрузки ресурсов Genshin Impact. Таких ошибок много, но и для них есть решение. На настоящий момент есть несколько проверенных решение:

После полной переустановки игры ошибка загрузки ресурсов Геншин Импакт больше не должна вас беспокоить, однако, убедитесь, что во время загрузки у вас не будут открыты сторонние программы и процессы, ведь это может привести к сбоям.

Источники:

Https://yakadr. ru/windows/oshibki/0x00000000-v-operatsionnoj-sisteme-windows. html

Https://genshin. ru/errors/vse-oshibki-v-genshin-impact

Я слежу за видеоуроком, где мне нужно создать пустое приложение ASP.NET Web с MVC, используя Visual Studio 2015, будучи новичком в мире ASP.NET, я следую шагу шаг.

Я успешно создал свой проект, на следующем шаге добавив представление из существующего Controller, я получил сообщение об ошибке в окне сообщения:

Ошибка:
Произошла ошибка при запуске выбранного генератора кода:
‘Неверный указатель (исключение из HRESULT: 0x80004003 (E_POINTER))’

Я погуглил проблему, нашел похожие проблемы, но ни одна из них не привела к четкому решению, некоторые похожие проблемы были выданы предыдущей версией VisualStudio, но, как я уже сказал, ни одной с четким решением.

Чтобы прояснить, что я испытал, вот что я сделал шаг за шагом:

Выбрано веб-приложение ASP.NET:

enter image description here

Выбран пустой шаблон с установленным флажком MVC:

enter image description here

Пытался Add View с контроллера:

enter image description here

Некоторые настройки …

enter image description here

Ошибка:

enter image description here

Что вызывает эту проблему и как ее решить?

Обновление:

Оказывается, даже пытаясь добавить представление вручную, я получаю ту же ошибку, добавить представление невозможно!

20 ответов

Лучший ответ

Попробуйте очистить ComponentModelCache, кеш будет восстановлен при следующем запуске VS.

  1. Закройте Visual Studio
  2. Удалите все в этой папке C: Users [your users name] AppData Local Microsoft VisualStudio 14.0 ComponentModelCache
  3. Перезапустите Visual Studio

14.0 предназначена для Visual Studio 2015. Это будет работать и для других версий.


75

VSB
4 Мар 2020 в 08:45

Я знаю, что это действительно старая тема, но я наткнулся на нее, работая над своей проблемой. Моя была вызвана тем, что я переименовал один из моих классов модели. Несмотря на то, что приложение было создано и работало нормально, когда я попытался добавить новый контроллер, я получил ту же ошибку. Что касается меня, я просто удалил класс, который я переименовал, добавил его обратно, и все было в порядке.


0

SkinnyPete63
27 Июл 2020 в 10:27

Моя проблема заключалась в типах, используемых в классе модели.

Используя такие типы:

    [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; }

Больше не работает в Генераторе кода. Мне пришлось удалить эти типы и строительные леса без них, а затем добавить их позже.

Глупо, [NotMapped] раньше работал при возведении лесов.

Используйте базовые типы: int, string, byte и т. Д. Без таких типов, как DateTime, List, HttpPostedFileBase и т. Д.


0

Rusty Nail
19 Мар 2019 в 20:55

Предположим, вы используете datacontext в DLL, ну, это был мой случай, и я не знаю, почему у меня такая же ошибка, как вы описываете, я решаю ее, создав datacontextLocal в бэкэнд-проекте. затем я передаю Dbset в правильный текст данных и удаляю локальный (вы можете оставить его там, если хотите, может быть полезно в будущем

Если вы готовы использовать его в локальном тексте данных, создайте новый, а затем передайте Dbset правильному


1

sGermosen
29 Сен 2017 в 11:59

Я работаю над приложением Core 3, и эта проблема всплывала при добавлении контроллера. Я выяснил, что пакет Microsoft.VisualStudio.Web.CodeGeneration.Design был обновлен с помощью библиотеки DLL framework .net 4.x. Обновление проекта до Core 3.1 устранило проблему.


0

Hoodlum
18 Дек 2019 в 20:11

В настоящее время я пытаюсь ознакомиться с MVC 4. Некоторое время я занимался разработкой MVC 5, но мне нужно знать MVC 4, чтобы подготовиться к сертификации MCSD. Я следую руководству через Pluralsight, ориентированному на гораздо более старые версии Entity Framework и MVC (видео было выпущено в 2013 году!)

Я столкнулся с той же самой ошибкой 2 часа назад и рвал волосы, пытаясь понять, что не так. К счастью, поскольку проект в этом руководстве не имеет смысла, я смог отступить на протяжении всего процесса, чтобы выяснить, что было причиной ошибки объекта ref not set, и исправить ее.

Я обнаружил ошибку в структуре моего фактического решения.

У меня был настроен веб-проект MVC (‘ Веб-приложение ASP.NET ( .NET Framework ) ‘), но у меня также было 2 библиотеки классов, одна из которых содержит мой доступ к данным. Layer, и один, содержащий настройку домена для моделей, подключенных к моей базе данных.

Оба они принадлежали к типу « Библиотека классов ( .NET Standard ) ».

Проекту MVC это не понравилось.

Как только я создал новые проекты типа « Class Library ( .NET Framework , скопировал все файлы из старых библиотек в новые и исправил ссылку для Веб-проект MVC, перестройка и повторная попытка позволили мне правильно сформировать представление.

Это может показаться очевидным исправлением, не помещайте проект .NET Standard вместе с проектом .NET Framework и ожидайте, что он будет работать нормально, но это может помочь другим решить эту проблему!


0

IfElseTryCatch
31 Авг 2018 в 13:58

На всякий случай кому интересно — решение с чистым кешем у меня не сработало. но мне удалось решить проблему, но удалил все фреймворки .Net в системе, а затем установил их обратно один за другим.


0

Leonid
15 Июн 2017 в 14:51

Удаление папки .vs внутри каталога решения сработало для меня.


0

Adam Hey
16 Дек 2019 в 16:54

Проблема была решена после установки EntityFramework из диспетчера пакетов nuget в мой проект. Пожалуйста, взгляните на свои ссылки на проекты, которые уже были добавлены EntityFramework. Наконец, я могу добавить представление с шаблоном после добавления EntityFramework в ссылку на проект.


0

Ei Ei Phyu
23 Окт 2019 в 07:38

Ни одно из этих решений не помогло мне. Я только что обновил Visual Studio (обновления были доступны), и вдруг все заработало.


0

Exel Gamboa
16 Окт 2019 в 02:58

У меня сработал простой перезапуск VS. Я просто закрыл VS и перезапустил.


0

Sajithd
19 Сен 2019 в 04:12

C:Users{WindowsUser}AppDataLocalMicrosoftVisualStudio16.0_8183e7d1ComponentModelCache

Удалите из этой папки VS 2019 ….


0

Farzad Sepehr
30 Авг 2019 в 17:01

Я столкнулся с аналогичной проблемой, из-за которой генерация кода не работала. Очевидно, у моих метаданных были неизвестные свойства или значения. Я должен признать, что не пробовал здесь все ответы, но кто действительно хочет переустановить vs или загрузить любой из многочисленных используемых пакетов Nuget.

У меня сработала очистка проекта (Build-> Clean Solution) Генератор использовал устаревшие двоичные файлы для создания контроллера и представлений. Очистка решения удалила устаревшие двоичные файлы и вуаля.


0

user3416682
28 Авг 2018 в 21:56

В ASP.NET Core проверьте, есть ли у вас пакет nuget Microsoft.VisualStudio.Web.CodeGeneration.Tools и соответствует ли он версии вашего проекта.


0

Oleksandr Kyselov
21 Авг 2018 в 08:45

Попробуйте очистить ComponentModelCache,

1.Закройте Visual Studio

2. удалите все в этой папке C: Users AppData Local Microsoft VisualStudio 14.0 ComponentModelCache

3. перезапустите Visual Studio

4. проверьте еще раз

Это также использовало VS2017 для получения решения


0

Deepak Savani
28 Май 2018 в 20:04

У меня такая же ошибка, но в VS 2017, когда я создаю контроллер. Сделал так же, как написал @ sh.alawneh. Также я пытался делать то, что написал @longday. Но это не сработало. Потом попробовал по-другому:

  • Щелкните правой кнопкой мыши целевую папку.
  • В списке выберите Добавить => Новый элемент.

Там я выбираю новый контроллер и он работает нормально.

Может я кому помогу.


5

Maksym Labutin
23 Дек 2019 в 08:18

У меня была эта проблема с другим сообщением об ошибке «-1 выходит за пределы ..»

Единственное, что у меня сработало, — это удалить проект из решения, щелкнув проект правой кнопкой мыши и выбрав «Удалить». Затем щелкните решение правой кнопкой мыши, «Добавить существующий проект» и выберите проект, чтобы перезагрузить его в решение.

После перезагрузки проекта я снова могу добавлять представления.


13

lucky.expert
29 Авг 2019 в 16:20

Я только что перезапустил свою визуальную студию, и это сработало.


0

Kurkula
21 Мар 2018 в 18:00

Я тоже ломал голову над этим, в моем случае я обнаружил, что в мой файл Web.config был добавлен дополнительный раздел. Комментируя это и перестраивая, я решил проблему, и теперь я смог добавить новый контроллер.


0

Icementhols
18 Май 2019 в 17:04

Щелкните правой кнопкой мыши проект под решением и выберите выгрузить проект,

Вы увидите, что проект выгружен, поэтому теперь щелкните его правой кнопкой мыши и нажмите загрузить проект.

Затем попробуйте добавить свой контроллер


2

MOHAMMAD OMAR
19 Ноя 2019 в 12:36

Понравилась статья? Поделить с друзьями:
  • При запуске героев 5 error
  • При запуске вот выдает ошибку видеокарты
  • При запуске выбранного генератора кода произошла ошибка сбой при восстановлении пакета
  • При запуске ворлд оф танк выдает ошибку видеокарты
  • При запуске ворлд оф танк выдает ошибку error