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

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,7119 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,69816 gold badges70 silver badges142 bronze badges

answered Mar 5, 2016 at 14:06

longday's user avatar

longdaylongday

4,0154 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

7311 gold badge14 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

5611 gold badge8 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,5174 gold badges23 silver badges27 bronze badges

answered Jul 27, 2016 at 17:17

sh.alawneh's user avatar

sh.alawnehsh.alawneh

6295 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

6481 gold badge7 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

1168 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

3123 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,4331 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

4785 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,32627 gold badges123 silver badges200 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,6943 gold badges34 silver badges55 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

5291 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,4721 gold badge20 silver badges23 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

5931 gold badge5 silver badges20 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

2912 silver badges16 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,79323 silver badges23 bronze badges

Try unload and reload project (solution).

answered Apr 17, 2022 at 6:51

Dee Nix's user avatar

Dee NixDee Nix

1701 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

8611 gold badge12 silver badges20 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,28813 silver badges21 bronze badges

I just turned off my v2ray proxy and it worked

answered Mar 1 at 12:40

Sur Khosh's user avatar

Sur KhoshSur Khosh

1151 silver badge8 bronze badges

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!!

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.

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.7k27 gold badges120 silver badges183 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 badges121 silver badges140 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,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; }

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

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.4k62 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.4k62 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,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 S's user avatar

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

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

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.4k62 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,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

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.7k27 gold badges120 silver badges183 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 badges121 silver badges140 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,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; }

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

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.4k62 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.4k62 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,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 S's user avatar

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

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

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.4k62 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,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

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,4919 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,38716 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,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

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

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

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

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

SkinnyPete63's user avatar

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

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,59318 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,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

Abrar ul Hassan's user avatar

1

Volodya_

14 / 12 / 3

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

Сообщений: 446

1

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

956 / 584 / 202

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

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

22.07.2021, 15:08

4

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

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

0

922 / 600 / 149

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

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

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

22.07.2021, 15:34

5

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

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

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

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

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

0

956 / 584 / 202

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

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

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

922 / 600 / 149

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

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

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

23.07.2021, 08:29

8

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

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

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

0

14 / 12 / 3

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

Сообщений: 446

23.07.2021, 13:16

 [ТС]

9

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

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

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

0

22 ответа

Проблема заключалась в повреждении каталога web.config и пакета.

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

Проблема заключалась в том, что обновления сильно загрузили мой файл конфигурации с множеством артефактов обновления, которые я закончил очисткой.

Вторая проблема заключалась в том, что старый проект также зависел от старых DLL, которые должны были быть уничтожены приложением пакета Nuget. Поэтому я уничтожил папки obj и bin, а затем папку пакета. После этого я смог восстановить старый проект и построить его чисто.

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

  • Возможно, пакет nuget имеет недостаток
  • Контроллер источника TFS заблокировал nuget от правильного обновления различных зависимостей.

С тех пор, прежде чем применять какие-либо обновления, я проверю все. Однако, поскольку я не обновлял EF через некоторое время, я не подтверждаю, что это разрешило проблему EF или леса.

Brian
22 янв. 2014, в 02:25

Поделиться

VS2013 Ошибка: произошла ошибка при запуске выбранного генератора кода: «Конфигурация для типа» SolutionName.Model.SalesOrder «уже был добавлен… ‘

У меня была эта проблема при работе через Pluralsight Course «Родительские данные с EF, MVC, Knockout, Ajax и Validation». Я пытался добавить Новый элемент леса с помощью шаблона MVC 5 Controller с представлениями, используя Entity Framework.

Класс контекста данных, который я использовал, включая переопределение метода OnModelCreating. Для переопределения требовалось добавить некоторые явные конфигурации столбцов базы данных, где значения по умолчанию EF были недостаточными. Это переопределение было простым, проработанным и отсутствием ошибок, но (как отмечено выше) это мешало генерации кода подсистемы Controller.

Решение, которое сработало для меня:

1 — я удалил (закомментировал) мое переопределение OnModelCreating и шаблон леса, заполненный без сообщений об ошибках, — мой код контроллера был сгенерирован, как ожидалось.

2 — Однако попытка создания проекта задохнулась, потому что «Модель изменилась». Поскольку мой код контроллера был теперь правильно сгенерирован, я восстановил (не комментировал) переопределение OnModelCreating и проект был создан и успешно запущен.

Bill B
17 авг. 2014, в 00:00

Поделиться

Я смог решить эту проблему и немного лучше понял, что происходит. Самое приятное то, что я могу воссоздать проблему и исправить ее, чтобы быть уверенным в моем объяснении здесь.
Решением было установить точно такую ​​же версию Entity Framework для проекта Data Access Layer и веб-проекта.

На моем уровне доступа к данным была установлена ​​платформа Entity Framework v6.0.2 с использованием NuGet, веб-проект не был установлен на платформе Entity Framework. При попытке создать контроллер веб-API с шаблоном Entity Framework Entity Framework устанавливается автоматически, но его старая версия 6.0.0. Я был удивлен, увидев, что две версии Entity Framework установлены, новее в моем проекте Data Layer и старше в моем веб-проекте. Однажды я удалил старую версию и установил новую версию в Web Project, проблема исчезла.

isingh
07 март 2014, в 20:13

Поделиться

Я проверил все мои проекты, и каждая из них имела ту же версию Entity Framework. В моем случае проблема заключалась в том, что один из моих проектов был нацелен на .Net 4.0, а остальные были .Net 4.5.

Решение:

  • Для каждого проекта в решении Project- > Properties- > Application: Установите Target Framework в .Net 4.5 (или что вам нужно).
  • Инструменты- > Управление пакетом NuGet для решения. Найти установленную «Entity Framework». Нажмите «Управление». Снимите отметку со всех проектов (обратите внимание на проекты, требующие EF). Теперь переустановите EF и проверьте, какие проекты вам нужны.
  • Очистить и восстановить решение.

RitchieD
01 май 2014, в 14:09

Поделиться

Я пробовал каждый ответ на каждом найденном мной сайте, и ничего не работало… до этого. Проводка поздно в случае, если кто-то вроде меня приходит и имеет тот же самый неприятный опыт, что и у меня.

Моя проблема была похожа на многие здесь, общее сообщение об ошибке при попытке использовать строительные леса, чтобы попытаться добавить новый контроллер (ef6, webapi). Сначала я смог использовать строительные леса примерно для 15 контроллеров, после чего он просто прекратил работать в один прекрасный день.

Окончательное решение:

  • Откройте свою рабочую папку на жестком диске для вашего решения.
  • Удалить все внутри папки BIN
  • Удалить все содержимое папки OBJ
  • Очистить решение, перестроить решение, добавить контроллер через строительные леса

Voila! (для меня)

erikrunia
13 май 2015, в 15:58

Поделиться

У меня такая же проблема.
Сначала столкнулся с этим, следуя по курсу Pluralsight «Данные родительского ребенка с EF, MVC, Knockout, Ajax и Validation».

Я использую MVC 5, EF 6.1.1 и фреймворк 4.5.2.

Даже после обновления моего VS2013 до обновления 4 эта ошибка все еще сохраняется.

Была возможность обойти эту неприятную проблему, изменив DbSet на IDbSet внутри класса DbContext.
Ответ был из здесь.

//From
public DbSet SalesOrders { get; set; }

//To
public IDbSet SalesOrders { get; set; }

scyu
14 нояб. 2014, в 11:28

Поделиться

Обычно это вызвано недопустимым файлом Web.config. У меня была та же проблема, и оказалось, что я случайно поменял блок комментариев HTML <!-- --> на блок комментариев на стороне сервера @* *@ (через действие «Заменить все» ).

И если вы разрабатываете приложение WinForms, попробуйте посмотреть App.config.

Moslem Ben Dhaou
25 май 2014, в 11:24

Поделиться

Для нас это имеет какое-то отношение к конфигурациям сборки, где у нас есть конфигурация сборки Debug | x64, с которой мы недавно переключились на использование, что, по-видимому, выглядело, когда строительные леса перестали работать.

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

Что сработало для нас (с использованием VS 2013 Express для Интернета на 64-битной Windows 7):

Он (строительные леса) НЕ работал в конфигурации Debug | x64 Build. Но делать следующее (и кажется, что каждый шаг необходим — не мог понять, как это сделать более оптимизированным образом), кажется, работает для нас.

  • Сначала переключитесь на Debug | x86 — используйте Solution (щелкните правой кнопкой мыши) Configuration Manager для всех проектов вашего решения. (Отладка | Любой процессор также может работать).
  • Очистите ваше решение.
  • Завершить работу Visual Studio. (не могу заставить его работать, если я пропущу это).
  • Откройте Visual Studio.
  • Откройте свое решение.
  • Создайте свое решение.
  • Теперь попробуйте добавить элементы леса; для нас это сработало в этот момент, мы больше не получили сообщение об ошибке, говорящее о том, что «произошла ошибка, выполняемая генератором выделенного кода».

Если вам нужно переключиться на конфигурацию незагружаемой сборки, вы можете сделать это, после того, как вы поднимете все, что вам нужно на данный момент. Мы вернулись к нашему Debug | x64 после строительных лесов, что нам нужно.

DWright
08 март 2015, в 00:58

Поделиться

Ничто из этого не помогло мне.

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

Я бы хотел, чтобы Microsoft выпустила меньше багги.

Jim Taliadoros
12 авг. 2014, в 02:20

Поделиться

Что сработало для меня, чтобы решить эту проблему: Закрыть решение, и откройте проект, щелкнув файл проекта, а не файл решения, добавьте свой контроллер и нарежьте своего дяди

Gerrie Pretorius
06 март 2014, в 10:30

Поделиться

Это обычно связано с форматом вашего Web.config

Восстановите решение и найдите в разделе Ошибки, вкладка Сообщения.
Если у вас есть проблемы с форматом с помощью web.config, вы увидите его там.
Исправьте его и повторите попытку.

Пример: у меня был connectionstring вместо connectionstring

Marko
12 дек. 2016, в 20:54

Поделиться

У меня возникла эта проблема при попытке добавить Api Controller в мое веб-приложение MVC ASP.NET по совершенно другой причине, чем другие ответы. Я случайно включил атрибут StringLength с объявлением IndexAttribute для свойства integer из-за операции копирования и вставки:

[Index]
[IndexAttribute("NumTrainingPasses", 0), StringLength(50)]
public int NumTrainingPasses { get; set; }

Как только я избавился от объявления IndexAttribute, я смог добавить Api Controller для модели, содержащей свойство оскорбления (NumTrainingPasses).

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

Произошла ошибка с запуском генератора кода:

Невозможно получить метаданные для «Owner.Models.MainRecord». Недвижимость |
«NumTrainingPasses» не является массивом String или Byte. Длина может быть равна
настроен для свойств массива String или Byte.

Robert Oschler
15 июль 2015, в 21:55

Поделиться

Я видел эту ошибку с новым проектом MVC5 при ссылке на модель из другого проекта. Проверка пути, EntityFramework.dll действительно существует. Это было только для чтения. Монитор процесса показал, что произошла ошибка при попытке удалить файл. Установка EntityFramework.dll в папке моих пакетов (копия, хранящаяся в исходном элементе управления) для записи, обходилась вокруг этой ошибки, но привела еще одну, заявив, что она не может загрузить сборку EntityFramework, потому что она не соответствует той, на которую ссылаются. Мой класс модели был определен в другом проекте, который использовал более старую версию инфраструктуры сущности. Проект MVC5 ссылался на EF 6, в то время как модель была из проектных ссылок EF 4.4. Модернизация до EF 6 в проекте модели исправила его для меня.

Lindsey
21 нояб. 2013, в 10:53

Поделиться

У меня была эта проблема в VS 2017. У меня была цель Platform (в свойствах проекта> Build> General), установленная на «x64». Scaffolding начал работать после изменения его на «Любой процессор».

billw
27 март 2019, в 10:47

Поделиться

Я знаю, что я опаздываю, но это было так расстраивать, поэтому я надеюсь, что это может немного помочь…

Моя проблема была похожа на много опыта здесь, общее сообщение об ошибке при попытке добавить новое представление или использовать строительные леса для добавления нового контроллера.
Я узнал, что mvc 5 и ef 6 modelbuilder не очень хорошие друзья:

Мое решение:
1.Комментируйте модельBuilder в своем классе Context.
Решение 2.Clean, решение для перестройки.
3.Add view и Controller через строительные леса
4. Uncomment modelbuilder.

Может быть, немного нетрадиционным — но это сработало! (для меня)

freddy
15 май 2016, в 11:03

Поделиться

У меня была такая же проблема, когда в моем MVC app EF reference property (в окне свойств) «Конкретная версия» была отмечена как False и в моем другом проекте (содержащем DBContext и models), который был переопределен из приложения MVC, что свойство ссылки EF был отмечен как «Истина». Когда я обозначил это как False, все было в порядке.

Iwona Kubowicz
15 нояб. 2015, в 11:57

Поделиться

  • vs2013 update 4
  • ef 5.0.0
  • ibm db2connector 10.5 fp 5

измените файл web.config следующим образом:
удалил провайдера из ef-тега:

<entityFramework>
</entityFramework>

добавлены теги строки подключения в разделах конфигурации:

</configSections>
<connectionStrings>
<add name=".." connectionString="..." providerName="System.Data.EntityClient" />
</connectionStrings>

gummylick
28 июнь 2015, в 04:38

Поделиться

Это случилось со мной, когда я попытался создать новый эшафот за пределами папки верхнего уровня для данного Area.

  • MyArea
     | — File.cs(попытался создать новый эшафот здесь. Ошибка.)

Я просто переустановил область и проблема исчезла:

  • AyArea (Добавить = > новый элемент леса)

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

P.Brian.Mackey
20 апр. 2015, в 17:17

Поделиться

У меня также есть эта проблема с MSVS2013 Update 4 и EF 6.0
Сообщение, которое я получал, было:

    there was an error running the selected code generator.
A configuration for type XXXX has already been added ...[]

У меня есть модель с 10 классами. Я без каких-либо проблем набросал элементы в начале проекта.

Через несколько дней, добавив функциональность, я попытался выставить еще один класс из модели, но ошибка не позволяла мне это делать.

Я попытался обновить MSVS от обновления 2 до обновления 4, закомментировать мой метод OnModelCreating и другие идеи, предложенные без везения.

Как временный способ продолжить проект, я создал другой проект asp.net, на который были вставлены мои классы моделей (я использую свободно api, поэтому на них мало комментариев) и успешно создал мой контроллер и представления.

После этого я вставил созданные классы в исходный проект и исправил некоторые ошибки (в основном имена dbset).

Кажется, что работает, хотя я полагаю, что все равно найду ошибки, связанные с отношениями между классами (из-за отсутствия свободной конфигурации при создании).

Я надеюсь, что это поможет другим пользователям.

user1839387
25 фев. 2015, в 13:08

Поделиться

Я часто сталкиваюсь с этой ошибкой, работая с MVC5 и EF, когда создаю модели и контексты в отдельном проекте (уровень доступа к данным), и я забываю добавить строку контекстного подключения к проекту MVC Web.Config.

John S
06 дек. 2014, в 07:30

Поделиться

Реконструкция решения работает для меня. перед восстановлением я нахожу ссылки на номер моего «ApplicationDbContext» равным нулю, что невозможно, поэтому переустановите решение, теперь все в порядке.

simon9k
10 сен. 2014, в 11:57

Поделиться

В случае, если это кому-то помогает, я переименовал пространство имен, в котором находилась модель, затем перестроил проект, затем переименовал его обратно и перестроил, а затем он сработал.

Adam Marshall
03 фев. 2014, в 16:00

Поделиться

Ещё вопросы

  • 0C ++: как преобразовать строковые векторные элементы в unsigned char?
  • 0Переполнение содержимого таблицы другими делителями
  • 0Чтение из файла в массив структур
  • 0Могу ли я получить имя последней вызванной функции API CUDA?
  • 1Как лучше хранить данные корзины?
  • 1Как напечатать максимальное значение символа?
  • 0Ошибки компиляции объекта c ++ LogFile
  • 1Python: переупорядочить словарь по первой половине / части ключа
  • 0Обновить ng-repeat строки при добавлении новых данных в источник с помощью parse.com
  • 0Запрос, где все значения одинаковы для определенного уникального идентификатора
  • 0Можете ли вы инициализировать поток в классе, который ссылается на функцию внутри этого класса?
  • 0MySQL группа, два условия, предел 1
  • 1Календарь пропускает 31 августа в действии (Calendar.DATE, false)
  • 0GEM Framework, или давайте изучать GCC
  • 0Как заставить typeAhead работать каждый раз при первом нажатии
  • 0Откуда берется значение x?
  • 0Выбор даты не работает при изменении индекса выпадающего списка
  • 0Запрос Mysql NOT IN не возвращает то, что я хочу
  • 0Как найти все файлы только для чтения, используя jQuery?
  • 1Загрузка файла на FTP-сервер не работает
  • 1Многопроцессорность выдает ошибку атрибута, почему?
  • 0получить обоих слизней из одинаковых категорий
  • 1Можем ли мы установить / исправить коэффициенты в уравнении регрессии в Python
  • 0Получить значение строки запроса из URL внутри большей строки с помощью PHP
  • 0Что такое «u0080-» и «u024F» в регулярном выражении проверки Jquery?
  • 0построить приложение для телефонной связи на нескольких языках
  • 0Исчезают шаблоны руля загрузки файлов jQuery
  • 0Target Один элемент с тем же именем класса, что и несколько элементов
  • 1com.microsoft.sqlserver.jdbc.SQLServerException: сбой входа для пользователя ‘sa’
  • 1Функция хеширования, совместимая с Arrays.hashCode
  • 1возникли проблемы с событиями щелчка флажка
  • 1JAXB Как проверить xml против большего количества схем
  • 1Сохраняйте один столбец, но используйте другие столбцы в Pandas Groupby и Agg
  • 1Проблемы с относительным расположением
  • 0Предложение по реализации инструмента чтения файлов
  • 0Я хочу, чтобы мои <p> были рядом друг с другом
  • 0Пользовательский C ++ Предикат и найти, если
  • 1Добавление оператора else в пары значений ключа словаря Javascript?
  • 0MonoDevelop (Ubuntu) и MySql
  • 1Не удалось загрузить файл или сборку WPFToolkit
  • 1Исключение комбинированного списка «Не удается найти столбец» в фильтре Bindingsource
  • 1Как изменить свойство переднего плана AvalonDock AnchorablePaneTitle ContentPresenter при автоматическом скрытии?
  • 1шаги для установки нового приложения Android на новое устройство HTC
  • 1Вход с ролью в Node.js и Express
  • 1Вызовите родительский метод из экземпляра
  • 1Сдвиг рядов в панде df
  • 0Массив объекта, как сделать выбор параметров
  • 0Как загрузить изображения тоже phpmyadmin ASP.Net
  • 1Как переопределить функцию компонента в Polymer 2?
  • 1Переключить / Case в Matlab на If / Else Python

Как самостоятельно исправить код ошибки 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

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

Произошла ошибка при запуске выбранного генератора кода:
— Доступ к тропе!—1—>
‘C:UsersXXXXXXXAppDataLocalTempSOMEGUIDEntityFramework.dll «отказано».

Я запускаю VS 2013 как администратор.

Я посмотрел на совместим ли MvcScaffolding с VS 2013 RC по командной строке? но похоже, это не решило проблему.

VS2013
C#5
MVC5
Новый проект стартовал в VS 2013.

21 ответов


ошибка VS2013: произошла ошибка при запуске выбранного генератора кода:
‘Конфигурация для типа’ SolutionName.Модель.Salesorder, которая уже
были добавлены …’

У меня была эта проблема при работе через курс Pluralsight «данные родитель-потомок с EF, MVC, Knockout, Ajax и Validation». Я пытался добавить Новый Деталь С помощью шаблона контроллер MVC 5 с представлениями, используя Entity Framework.

класс контекста данных, который я использовал, включая переопределение метода OnModelCreating. Переопределение было необходимо для добавления некоторых явных конфигураций столбцов базы данных, где значения по умолчанию EF были неадекватными. Это переопределение было простым, работающим и без ошибок, но (как отмечалось выше) это мешало генерации кода лесов контроллера.

решение, которое сработало для меня:

1-я удалил (прокомментировал) мое переопределение OnModelCreating и шаблон лесов завершен без сообщений об ошибках — мой код контроллера был сгенерирован, как ожидалось.

2-однако, пытаясь построить проект, задохнулся, потому что «модель изменилась». Поскольку мой код контроллера был теперь правильно сгенерирован, я восстановил (без комментариев) переопределение OnModelCreating, и проект был построен и успешно запущен.


проблема была с поврежденной сетью.каталог конфигурации и пакетов.

Я создал новый проект и скопировал свои файлы кода в новый рабочий проект, позже я вернулся и запустил различия в файлах конфигурации и папку diff в самом проекте.

проблема заключалась в том, что обновления сильно выбросили мой конфигурационный файл с большим количеством артефактов обновления, которые я в конечном итоге очистил.

вторая проблема заключалась в том, что старый проект тоже висит на более старые библиотеки DLL, которые должны были быть стерты с применением пакета Nuget. Поэтому я вытер папки obj и bin, а затем папку пакета. После того, как это было сделано, я смог получить старый проект отремонтирован и здание чисто.

Я не изучал, почему файл конфигурации или папка пакета были настолько borked, но я предполагаю, что это одна из двух вещей.

  1. возможно, пакет nuget имеет недостаток
  2. система управления версиями TFS заблокировала nuget от правильного обновления различных зависимостей.

с тех пор, прежде чем применять какие-либо обновления, я проверяю все. Однако, поскольку я не обновил EF в то время, я нет доказательств того, что это решило мою проблему EF или лесов.


Я смог решить эту проблему и немного лучше понять, что происходит. Лучшая часть заключается в том, что я могу воссоздать проблему и устранить ее, чтобы быть уверенным в моих объяснениях.
разрешение состояло в том, чтобы установить точно такую же версию Entity Framework как для проекта уровня доступа к данным, так и для веб-проекта.

мой уровень доступа к данным имел Entity Framework v6.0.2 установленный с помощью NuGet, веб-проект не был установлен Entity Framework. При попытке создать контроллер веб-API с шаблоном Entity Framework Entity Framework устанавливается автоматически, но его более старая версия 6.0.0. Я был удивлен, увидев две версии Entity Framework, более новые в моем проекте уровня данных и более старые в моем веб-проекте. Однажды я удалил старую версию и установил более новую версию в веб-проекте, проблема ушла.


Я проверил все свои проекты, и каждый из них имел ту же версию Entity Framework. В моем случае проблема заключалась в том, что один из моих проектов был нацелен на .Net 4.0, в то время как остальные были .Net 4.5.

устранение:

  1. для каждого проекта в проекте решения — > свойства — >приложение: установите целевую платформу на .Net 4.5 (или что вам нужно).
  2. инструменты — > управление пакетом NuGet для решения. Найдите Установленную «Entity Framework». И нажмите кнопку Управление. Снимите флажок все проекты (обратите внимание на проекты, требующие EF). Теперь, повторно управлять EF и проверить, что проекты, которые вам нужны.
  3. очистить и перестроить решение.

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

моя проблема была похожа на многие здесь, общее сообщение об ошибке при попытке использовать леса, чтобы попытаться добавить новый контроллер (ef6, webapi). Первоначально я мог использовать леса примерно для 15 контроллеров, после этого он просто перестал работать один день.

финал Решение:

  1. открыть рабочую папку на жестком диске вашего решения.
  2. удалить все внутри папки BIN
  3. удалить все внутри папки OBJ
  4. чистое решение, перестроить решение, добавить контроллер через леса

вуаля! (для меня)


это обычно вызвано недопустимым . У меня была такая же проблема, и оказалось, что я нечаянно изменил блок комментариев HTML <!-- --> к блоку комментариев на стороне сервера @* *@ (через действие заменить все).

и в случае, если вы разрабатываете приложение WinForms, попробуйте посмотреть на App.config.

4

автор: Moslem Ben Dhaou


У меня точно такая же проблема.
Впервые столкнулся с этим, следуя по курсу Pluralsight «данные родитель-потомок с EF, MVC, нокаутом, Ajax и проверкой».

Я использую MVC 5, EF 6.1.1 и framework 4.5.2.

даже после обновления моего VS2013 до обновления 4 Эта ошибка все еще сохраняется.

удалось обойти эту неприятную проблему, изменив DbSet на IDbSet внутри класса DbContext.
Ответ был первоначально от здесь.

//From
public DbSet SalesOrders { get; set; }

//To
public IDbSet SalesOrders { get; set; }

Что сработало для меня, чтобы решить эту проблему: закройте решение и откройте проект, щелкнув файл проекта, а не файл решения, добавьте контроллер и качайте своего дядю

2

автор: Gerrie Pretorius


ничто из вышеперечисленного не помогло мне.

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

Я хочу, чтобы Microsoft выпустила меньше багги-кода.


для нас это имеет какое-то отношение к конфигурациям сборки, где у нас есть конфигурация сборки Debug|x64, которую мы недавно переключили на использование, что в ретроспективе казалось, когда леса перестали работать.

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

что работало для нас (используя VS 2013 Express for Web на 64 бит Windows 7):

Это (леса) было не работа в конфигурации сборки Debug/x64. Но делаю следующее (И кажется, что каждый шаг необходим, не мог выяснить, как сделать это более простым способом), кажется, работает для нас.

  1. сначала переключитесь на Debug / x86—используйте диспетчер конфигурации решения (щелкните правой кнопкой мыши) для всех проектов в вашем решении. (Debug / любой процессор также может работать).
  2. очистить решение.
  3. завершение работы Visual Studio. (не могу заставить его работать, если я пропущу этого).
  4. Открыть Visual Studio.
  5. откройте свое решение.
  6. построить решение.
  7. теперь попробуйте добавить элементы лесов; для нас это сработало на данный момент, мы больше не получили сообщение об ошибке, говорящее что-то о «была ошибка при запуске выбранного генератора кода».

Если вам нужно вернуться к конфигурации сборки лесов-нерабочей, вы можете сделать это после того, как вы построили все, что вам нужно на данный момент. Мы переключились обратно на наш Debug / x64 после лесов, что нам нужно.


Я видел эту ошибку с новым проектом MVC5 при ссылке на модель из другого проекта. Проверка пути, EntityFramework.dll файлы действительно существуют. Но только для чтения. Монитор процессов показал, что произошла ошибка при попытке удалить файл. Установка и EntityFramework.dll в папке «Мои пакеты» (копия, хранящаяся в системе управления версиями) для записи обошла эту ошибку, но вызвала другую, сказав, что она не может загрузить сборку EntityFramework, потому что она не соответствует той упоминаемый. Мой класс модели был определен в другом проекте, который использовал более старую версию Entity framework. Проект MVC5 ссылался на EF 6, в то время как модель была из проекта ссылки EF 4.4. Обновление до EF 6 в проекте модели исправило это для меня.


У меня была эта проблема при попытке добавить контроллер Api в мой MVC ASP.NET веб-приложение по совершенно другой причине, чем другие приведенные ответы. Я случайно включил StringLength С IndexAttribute объявление для целочисленного свойства из-за операции копирования и вставки:

[Index]
[IndexAttribute("NumTrainingPasses", 0), StringLength(50)]
public int NumTrainingPasses { get; set; }

Как только я избавился от IndexAttribute объявление я смог добавить контроллер Api для модели, которая содержала оскорбительное свойство (NumTrainingPasses).

чтобы помочь поисковым системам, вот полное сообщение об ошибке, которое я получил, прежде чем я исправил проблему:

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

не удалось получить метаданные для владельца.Модели.MainRecord’. Свойство
«NumTrainingPasses»не является строковым или байтовым массивом. Длина может быть
настроен для свойств массива строк или байтов.


обычно это связано с форматом вашего веб-сайта.config

перестроить решение и поиск в разделе ошибки, сообщения вкладки.
Если у вас возникли проблемы с веб.config вы увидите его там.
Исправьте это и повторите попытку.

пример: у меня connectionstring вместо connectionString


Если это кому-то поможет, я переименовал пространство имен, в котором находилась модель, затем перестроил проект, затем снова переименовал его и перестроил, а затем он работал.


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


Я часто сталкиваюсь с этой ошибкой, работая с MVC5 и EF, когда я создаю модели и контекст в отдельном проекте (мой уровень доступа к данным), и я забываю добавить строку контекстного подключения к веб-сайту проекта MVC.Конфиг.


У меня также есть эта проблема с Msvs2013 Update 4 и EF 6.0
Сообщение, которое я получил, было:

    there was an error running the selected code generator.
A configuration for type XXXX has already been added ...[]

У меня есть модель с 10 класса. Я без проблем собрал элементы в начале проекта.

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

Я попытался обновить MSVS от обновления 2 до обновления 4, прокомментируйте мой метод OnModelCreating и другие идеи, предложенные безрезультатно.

в качестве временного способа продолжения проекта я создал другой asp.net проект, вставил туда мои классы моделей (я использую fluent api, поэтому на них мало аннотаций) и успешно создал мой контроллер и представления.

после этого я вставил созданные классы в исходный проект и исправил некоторые ошибки (в основном имена dbset).

Кажется, это работает, хотя я полагаю, что я буду все еще находите ошибки, связанные с отношениями между классами (из-за отсутствия плавной конфигурации при создании).

Я надеюсь, это поможет другим пользователям.


Это произошло со мной, когда я попытался создать новый эшафот вне папки верхнего уровня для данного площадью.

  • MyArea
    | — Папка.cs (попытался создать здесь новый эшафот. Неудача.)

Я просто повторно выбрал свою область, и проблема ушла:

  • AyArea (Add => новый элемент ремонтины)

обратите внимание, что после генерации лесов вы попадете в место, где вы не сможете создайте новый помост без повторного выбора области сначала (по крайней мере, в VS 2013).


  • vs2013 обновления 4
  • ef 5.0.0
  • ibm db2connector 10.5 fp 5

изменить сети.конфигурационный файл как таковой:
удален поставщик / ы из тега ef:

<entityFramework>
</entityFramework>

добавлены теги строк подключения в разделах конфигурации:

</configSections>
<connectionStrings>
<add name=".." connectionString="..." providerName="System.Data.EntityClient" />
</connectionStrings>

У меня была та же проблема, когда в моем MVC app EF reference property (в окне свойств) «конкретная версия» была отмечена как False и в моем другом проекте (содержащем DBContext и модели), который был рефренирован из MVC app, что EF reference property был отмечен как True. Когда я отметил Это как ложь, все было в порядке.


Я знаю, что я поздно, но это было так неприятно, поэтому я надеюсь, что это может немного помочь …

моя проблема была похожа на многие здесь, универсальное сообщение об ошибке при попытке добавить новый вид или использование лесов для добавления нового контроллера.
я узнал, что MVC 5 и EF 6 modelbuilder не являются хорошими друзьями:

Мое Решение:
1.Прокомментируйте modelBuilder в своем классе контекста.
2.Чистое Решение, Перестроить Решение.

3.Добавить представление и контроллер через леса
4. Раскомментируйте в modelbuilder.

может быть, немного необычный, но он работал! (для меня)


Volodya_

14 / 12 / 3

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

Сообщений: 446

1

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



1010 / 628 / 213

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

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

22.07.2021, 15:08

4

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

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



0



979 / 645 / 161

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

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

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

22.07.2021, 15:34

5

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

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

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

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

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



0



1010 / 628 / 213

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

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

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



979 / 645 / 161

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

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

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

23.07.2021, 08:29

8

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

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

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



0



14 / 12 / 3

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

Сообщений: 446

23.07.2021, 13:16

 [ТС]

9

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

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

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



0



  • При запуске вотч догс выдает ошибку
  • При запуске восстановления системы выдает ошибку 0x81000203
  • При запуске ворлд оф танк выдает ошибку видеокарты
  • При запуске ворлд оф танк выдает ошибку application has stopped working
  • При запуске ворлд оф танк выдает ошибку application has failed to start because