Меню

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

I am trying to add controller to my solution in ASP.NET Core project:

When I try to do so I get this error:

I get the same message for adding minimal dependencies and full dependencies for controller.

Wai Ha Lee's user avatar

Wai Ha Lee

8,41977 gold badges60 silver badges90 bronze badges

asked Jun 12, 2017 at 22:33

user8038446's user avatar

5

I also had this issue. «Add Controller>API Controller with actions, using Entity Framework» would give the «Package Restore Failed» error.

As Anish stated, it seems to be due to package versions being mis-aligned. I was able to resolve this issue using «Manage NUGET Packages for Solution», then performing an «Update All». This set my AspNetCore version to 2.1.5 and resolved my «Package Restore Failed» error, but then led to another error, «NETCore version 2.1.5 not found». Apparently the scaffolding code generator needs the AspNetCore and the NETCore versions to be in sync, so I manually downloaded and installed the NETCore version 2.1.5 from Microsoft Downloads. This worked, and I was finally able to generate Controllers.

answered Oct 17, 2018 at 14:29

Scott Duncan's user avatar

Scott DuncanScott Duncan

9811 gold badge10 silver badges22 bronze badges

4

I was getting the same error while making a new controller.
I’ve fixed it like this.
Actually, VS only had the Offline Package source and could not resolve the packages needed.

Add the online reference:
Tools > nuget package manager > package manager settings > Package Sources

Add source: https://api.nuget.org/v3/index.json

answered Aug 18, 2019 at 5:47

Drashtant Solanki's user avatar

1

If no answer works for you, try running the code generator from the command line.

For my sln with multiple projects, with net 5 and some NuGet packages of 5.0.5 and some of 5.0.2, Only code generator through the command line worked. Make Sure it is installed.

or install it by the following command

dotnet tool install -g dotnet-aspnet-codegenerator

or update it by the following command

dotnet tool update -g dotnet-aspnet-codegenerator

The basic code generator commands can be found here

Some of them are:

Generator           Operation
area                Scaffolds an Area
controller          Scaffolds a controller
identity            Scaffolds Identity
razorpage           Scaffolds Razor Pages
view                Scaffolds a view

For example:

dotnet-aspnet-codegenerator identity --dbContext MyDbContextClass

To get help:

dotnet-aspnet-codegenerator [YourGenerator] -h

answered Apr 27, 2021 at 22:45

Sayyed Dawood's user avatar

2

  1. VS2019 [5.0].

  2. Update NuGet Packages (Tools -> Nuget Package Manager -> Manage
    NuGet packages for solution -> Click on the Updates tab, select all
    and run update.

  3. Solution -> Clean

  4. solution -> Build

  5. create a Controller.

I try everything but the above method work for me

answered Jan 2, 2021 at 17:55

nitin shinde's user avatar

I encountered this issue with net5.0, specifically against version 5.0.5 of some dependencies. I downgraded my nuget packages from 5.0.5 to 5.0.4 for these:

"Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="5.0.4"
"Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="5.0.4"
"Microsoft.AspNetCore.Identity.UI" Version="5.0.4" 
"Microsoft.EntityFrameworkCore.Tools" Version="5.0.4"

Dharman's user avatar

Dharman

29.2k21 gold badges79 silver badges131 bronze badges

answered Apr 12, 2021 at 12:15

wazdev's user avatar

wazdevwazdev

3234 silver badges11 bronze badges

4

I just recently ran into the same issue.

I resolved it by eventually taking a look at each individual .csproj files included in my solution and fixing all the versions of the microsoft libraries that were included.

I changed the metapackage that i was referencing from «Microsoft.AspNetCore.All» to «Microsoft.AspNetCore.App», i then loaded up the reference list on nuget for the «App» package and removed any references to libraries that are already included in the metapackage.

I then made sure that i fixed the versions of any outstanding packages to match the version of the metapackage that the project automatically chooses ie in my case 2.2.0.

Something that tripped me up was that if you have multiple projects included in your solution you need to make sure that they reference the same metapackage as if there is a version mismatch between projects included in your solution you will get this issue too.

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.2.5" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.3" />
  </ItemGroup>

Changed to this.

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.0" />
  </ItemGroup>

answered Jun 26, 2019 at 11:05

Darryn Hosking's user avatar

Darryn HoskingDarryn Hosking

2,9782 gold badges18 silver badges20 bronze badges

2

I just had this problem whilst adding a controller to a Core API with Entity Framework project. I’m using VS 16.8.5 with the most recent EF core, version 5.03. The class containing my DBContext class referenced EF 5.03 .

I (eventually!) noticed whilst browsing Nuget that the various code generation packages (none of which were referenced in my .csproj file, I think because ASP.Net core ships as a framework since 3.0 but correct me if I am wrong someone!), and in particular Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCode were 5.02. I didn’t touch my ASP.Net project, instead I dowgraded the other EF projects to 5.02 and it solved the problem.

answered Feb 16, 2021 at 17:48

Peter's user avatar

PeterPeter

618 bronze badges

I had resolved it by update two files

Microsoft.VisualStudio.Web.CodeGeneration
and
Microsoft.VisualStudio.Web.CodeGeneration.Design

. Its version should be match with other packages version in application.

answered Jul 10, 2020 at 13:38

Trident's user avatar

TridentTrident

311 silver badge9 bronze badges

Just update the NUGET packages from the Nuget Package Manager.

answered Aug 24, 2020 at 11:42

Mamoon Rasheed's user avatar

i have same error. and Update NuGet Packages (Tools -> Nuget Package Manager -> Manage NuGet packages for solution -> Click on installed.
You need select Version with notice Dependencies.

Example my option is fine with:

Microsoft.AspNetCore.Identity.EntityFramework Core with version 3.1.12

Microsoft.EntityFrameworkCore.Tools with version 3.1.12

Microsoft.EntityFrameworkCore.SqlServer with version 3.1.12

Microsoft.VisualStudio.Web.CodeGeneration.Design with version 3.1.5

answered Feb 27, 2021 at 18:00

ToanTV's user avatar

ToanTVToanTV

1111 silver badge3 bronze badges

1

I had the problem with a blazor server application version 5.0.5 and Microsoft Identity scaffolding. The highest available version of the CodeGeneration.Design package was 5.0.2, so i downgraded the other Microsoft packages (specially EntityFramework) to 5.0.2 and it solved the problem.

answered Apr 17, 2021 at 21:46

Andi's user avatar

AndiAndi

212 bronze badges

2

Had exactly same problem, in my situation CodeGenerator was missing

I have added this item into ItemGroup in .csproj

<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.0" />

answered Jul 5, 2019 at 11:21

Whistler's user avatar

WhistlerWhistler

1,8374 gold badges27 silver badges50 bronze badges

What fixed it for me after I couldn’t scaffold IdentityFramework was by

  1. Checking VS2019 for updates.
  2. Update NuGet Packages (Tools -> Nuget Package Manager -> Manage NuGet packages for solution -> Click on the updates tab, select all and run update.
  3. Retry scaffolding identity

answered Jun 28, 2020 at 13:27

Joshua Tromp's user avatar

Cleaning the solution showed me an error of NuGet packages needed to be updated! I updated them and build the solution. Build Successful and I was able to create the controller class.

answered May 25, 2021 at 7:11

joekevinrayan96's user avatar

Trying to add MVC controller with views using EF for MVC project using Net5.0.

Using the following NuGet packages specific versions worked for me, while the problem was solved by using less version than the version of Microsoft.EntityFrameworkCore, for both Microsoft.EntityFrameworkCore.SqlServer and Microsoft.EntityFrameworkCore.Tools, these packages are referenced in the MVC project.

The correct packages are:

<ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="5.0.7" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.7" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.6" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.6">
           <PrivateAssets>all</PrivateAssets>
           <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
            </PackageReference>
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.7" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="5.0.2" />   
</ItemGroup>

answered Jun 18, 2021 at 1:39

Ashraf Sada's user avatar

Ashraf SadaAshraf Sada

4,3712 gold badges44 silver badges46 bronze badges

I also faced this same error when i was trying to scaffold identity template. I resolve this issue by updating nuget packages of the two major project of concerns(I mean the the two projects that has something to do with what i was to implement).

answered Jul 30, 2021 at 13:16

sammy Akinsoju's user avatar

I am also facing this issue.

Please follow this step,

  • Clean Your Solution
  • Open Nuget Manager
  • Check this version Microsoft.EntityFrameworkCore (I am using 5.0.8)
  • Check this version Microsoft.EntityFrameworkCore.Design (I am using 5.0.8)
  • Check this version Microsoft.EntityFrameworkCore.Tools (I am using 5.0.8)
  • Check this version Microsoft.EntityFrameworkCore.SqlServer (I am using 5.0.8)
  • Check this version Microsoft.VisualStudio.Web.CodeGeneration.Design (I am using 5.0.2)

Check this image also

  • After that Rebuild your solution and Create Scaffolding Controller

answered Aug 14, 2021 at 10:59

Abdulla Sirajudeen's user avatar

1

The problem is that you have some of the older versions of nuget pacakges installed in your project and when you try to scaffold the Asp.net core tries to install the latest packages which are required for scaffolding at this point Asp.net core throws such exception.

I suggest you to update your nuget packages and than try scafolding.

Wai Ha Lee's user avatar

Wai Ha Lee

8,41977 gold badges60 silver badges90 bronze badges

answered Sep 23, 2020 at 13:32

Mohammed Rehan Javed Abdul Kar's user avatar

I know that some of you might still facing the same issue,
I just did the next in VS 2022,

1- Checked the depencendies on the current project.
enter image description here

2- Remove all of them

3- Go to dependencies
add a lower version

enter image description here

and the clean the solution and add the views.

answered Aug 15, 2022 at 19:14

Jose Antonio's user avatar

1

I also faced the same issue, Here is How I solved the Issue

There was an error running the selected code generation, ‘Package restore failed. Rolling back package canges for web’

1— Check if your Solution has multiple projects, please check their Target Dot.net Framework.(in my case it was .Net Standard 1.6 for class libraries & .NetCoreApp 1.0 for Web Project, I changed it to .NetCoreApp 1.1)

2— After having the same framework, clean the web project, Rebuilt and Add new Controller.

If its successful fine otherwise You might encounter another error e.g

‘There was an error running the code generator: ‘No executable found matching command «dotnet-aspnet-codegenerator»‘

If you have project.json file open it other wise open .csproj.user project in note pad, please add following


Please note based on your .net version you might have different version no.

You may find instruction in ScaffoldingReadMe.txt file if its generated in your project

answered Aug 17, 2017 at 4:12

Aamir's user avatar

AamirAamir

68510 silver badges11 bronze badges

All I had to do was open the properties of my web project and change the TargetFramework from 2.1 to 2.2. Or to match whatever version of the framework your business and object layer are using.

answered May 30, 2019 at 14:22

BBoyd's user avatar

BBoydBBoyd

411 bronze badge

Had the same problem, but updating all the NuGet Packages has solved the problem.
Right click on <your project name> file -> Manage NuGet Packages -> Updates -> Select all packages -> Update

answered Apr 27, 2020 at 9:13

Maksym Voloshko's user avatar

I’m running .NET Core (and Entity Framework Core) 3.1.x.

I got this exact error and tried updating all the nuget packages and other relevant solutions already mentioned in the answers here.

The issue was simply that my database server was not running (it runs on a local VM). In other words, my database context (i.e. ApplicationDbContext) mentioned in the ‘Add Controller…’ window, was not able to access the db. Once I started the db server, my scaffolding created without issue.

Keep also in mind, the model/class (i.e. table) that the controller and views were referencing had not been created yet (I hadn’t run add-migration yet). So, it just needed the db connection only.

It’s kind of a silly (obvious?) solution, but very misleading when looking at the ‘Package Restore Failed’ error message.

answered Jun 9, 2020 at 15:56

Sum None's user avatar

Sum NoneSum None

1,9732 gold badges23 silver badges31 bronze badges

I had a similar issue with entity framework core sqlite nuget packages. I installed sqlite and sqlite core packages fixed this. Probably a needy package is missing. Also make sure SQL Server and Server Agent are running. Check those on SQL Server Configuration > SQL Server Services > Right click on SQL Server or Server Agent and start the service then restart the server. Guess this might help someone

answered Aug 11, 2020 at 7:32

FF new's user avatar

FF newFF new

1031 gold badge1 silver badge11 bronze badges

My solution
-Vs2019 all nuget packages upgrade

answered Sep 21, 2020 at 21:21

wasdoska's user avatar

As someone mentioned earlier, I updated all NuGet packages from Tools->Nuget Package Manager -> Manage NuGet Packages for Solution -> Updates tab -> Update All. I was then able to add a controller with EF and have VS generate the associated views.

answered Oct 13, 2020 at 13:40

Phillip's user avatar

Just update all Nuget Packages , Clean Solution and the rebuild solution. It solve the issues for me.

answered Jan 30, 2021 at 15:26

vsharma10286's user avatar

I just updated EntityFrameworkCore from Version 3.1.10 to 3.1.13 and it solved the problem. My Project file looks like:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.13" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="3.1.13" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.13" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.13">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.5" />
  </ItemGroup>

</Project>

answered May 3, 2021 at 6:59

Rahim's user avatar

RahimRahim

7796 silver badges6 bronze badges

I had this same issue when creating a new ‘Identity’ scaffolded item.
I managed to get this working by removing everything within the <ItemGroup> tags within the csproj file and running the code generator. The generator then installs packages that it needs.

answered May 22, 2021 at 10:27

Hannah's user avatar

HannahHannah

3315 silver badges8 bronze badges

In case you are using .net 5.0.14, downgrading every packages with version 5.0.14 from 5.0.14 to 5.0.12 fixed the problem for me.

answered Mar 10, 2022 at 7:15

KodFun's user avatar

KodFunKodFun

3033 silver badges8 bronze badges

I am trying to add controller to my solution in ASP.NET Core project:

When I try to do so I get this error:

I get the same message for adding minimal dependencies and full dependencies for controller.

Wai Ha Lee's user avatar

Wai Ha Lee

8,41977 gold badges60 silver badges90 bronze badges

asked Jun 12, 2017 at 22:33

user8038446's user avatar

5

I also had this issue. «Add Controller>API Controller with actions, using Entity Framework» would give the «Package Restore Failed» error.

As Anish stated, it seems to be due to package versions being mis-aligned. I was able to resolve this issue using «Manage NUGET Packages for Solution», then performing an «Update All». This set my AspNetCore version to 2.1.5 and resolved my «Package Restore Failed» error, but then led to another error, «NETCore version 2.1.5 not found». Apparently the scaffolding code generator needs the AspNetCore and the NETCore versions to be in sync, so I manually downloaded and installed the NETCore version 2.1.5 from Microsoft Downloads. This worked, and I was finally able to generate Controllers.

answered Oct 17, 2018 at 14:29

Scott Duncan's user avatar

Scott DuncanScott Duncan

9811 gold badge10 silver badges22 bronze badges

4

I was getting the same error while making a new controller.
I’ve fixed it like this.
Actually, VS only had the Offline Package source and could not resolve the packages needed.

Add the online reference:
Tools > nuget package manager > package manager settings > Package Sources

Add source: https://api.nuget.org/v3/index.json

answered Aug 18, 2019 at 5:47

Drashtant Solanki's user avatar

1

If no answer works for you, try running the code generator from the command line.

For my sln with multiple projects, with net 5 and some NuGet packages of 5.0.5 and some of 5.0.2, Only code generator through the command line worked. Make Sure it is installed.

or install it by the following command

dotnet tool install -g dotnet-aspnet-codegenerator

or update it by the following command

dotnet tool update -g dotnet-aspnet-codegenerator

The basic code generator commands can be found here

Some of them are:

Generator           Operation
area                Scaffolds an Area
controller          Scaffolds a controller
identity            Scaffolds Identity
razorpage           Scaffolds Razor Pages
view                Scaffolds a view

For example:

dotnet-aspnet-codegenerator identity --dbContext MyDbContextClass

To get help:

dotnet-aspnet-codegenerator [YourGenerator] -h

answered Apr 27, 2021 at 22:45

Sayyed Dawood's user avatar

2

  1. VS2019 [5.0].

  2. Update NuGet Packages (Tools -> Nuget Package Manager -> Manage
    NuGet packages for solution -> Click on the Updates tab, select all
    and run update.

  3. Solution -> Clean

  4. solution -> Build

  5. create a Controller.

I try everything but the above method work for me

answered Jan 2, 2021 at 17:55

nitin shinde's user avatar

I encountered this issue with net5.0, specifically against version 5.0.5 of some dependencies. I downgraded my nuget packages from 5.0.5 to 5.0.4 for these:

"Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="5.0.4"
"Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="5.0.4"
"Microsoft.AspNetCore.Identity.UI" Version="5.0.4" 
"Microsoft.EntityFrameworkCore.Tools" Version="5.0.4"

Dharman's user avatar

Dharman

29.2k21 gold badges79 silver badges131 bronze badges

answered Apr 12, 2021 at 12:15

wazdev's user avatar

wazdevwazdev

3234 silver badges11 bronze badges

4

I just recently ran into the same issue.

I resolved it by eventually taking a look at each individual .csproj files included in my solution and fixing all the versions of the microsoft libraries that were included.

I changed the metapackage that i was referencing from «Microsoft.AspNetCore.All» to «Microsoft.AspNetCore.App», i then loaded up the reference list on nuget for the «App» package and removed any references to libraries that are already included in the metapackage.

I then made sure that i fixed the versions of any outstanding packages to match the version of the metapackage that the project automatically chooses ie in my case 2.2.0.

Something that tripped me up was that if you have multiple projects included in your solution you need to make sure that they reference the same metapackage as if there is a version mismatch between projects included in your solution you will get this issue too.

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.2.5" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.3" />
  </ItemGroup>

Changed to this.

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.0" />
  </ItemGroup>

answered Jun 26, 2019 at 11:05

Darryn Hosking's user avatar

Darryn HoskingDarryn Hosking

2,9782 gold badges18 silver badges20 bronze badges

2

I just had this problem whilst adding a controller to a Core API with Entity Framework project. I’m using VS 16.8.5 with the most recent EF core, version 5.03. The class containing my DBContext class referenced EF 5.03 .

I (eventually!) noticed whilst browsing Nuget that the various code generation packages (none of which were referenced in my .csproj file, I think because ASP.Net core ships as a framework since 3.0 but correct me if I am wrong someone!), and in particular Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCode were 5.02. I didn’t touch my ASP.Net project, instead I dowgraded the other EF projects to 5.02 and it solved the problem.

answered Feb 16, 2021 at 17:48

Peter's user avatar

PeterPeter

618 bronze badges

I had resolved it by update two files

Microsoft.VisualStudio.Web.CodeGeneration
and
Microsoft.VisualStudio.Web.CodeGeneration.Design

. Its version should be match with other packages version in application.

answered Jul 10, 2020 at 13:38

Trident's user avatar

TridentTrident

311 silver badge9 bronze badges

Just update the NUGET packages from the Nuget Package Manager.

answered Aug 24, 2020 at 11:42

Mamoon Rasheed's user avatar

i have same error. and Update NuGet Packages (Tools -> Nuget Package Manager -> Manage NuGet packages for solution -> Click on installed.
You need select Version with notice Dependencies.

Example my option is fine with:

Microsoft.AspNetCore.Identity.EntityFramework Core with version 3.1.12

Microsoft.EntityFrameworkCore.Tools with version 3.1.12

Microsoft.EntityFrameworkCore.SqlServer with version 3.1.12

Microsoft.VisualStudio.Web.CodeGeneration.Design with version 3.1.5

answered Feb 27, 2021 at 18:00

ToanTV's user avatar

ToanTVToanTV

1111 silver badge3 bronze badges

1

I had the problem with a blazor server application version 5.0.5 and Microsoft Identity scaffolding. The highest available version of the CodeGeneration.Design package was 5.0.2, so i downgraded the other Microsoft packages (specially EntityFramework) to 5.0.2 and it solved the problem.

answered Apr 17, 2021 at 21:46

Andi's user avatar

AndiAndi

212 bronze badges

2

Had exactly same problem, in my situation CodeGenerator was missing

I have added this item into ItemGroup in .csproj

<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.0" />

answered Jul 5, 2019 at 11:21

Whistler's user avatar

WhistlerWhistler

1,8374 gold badges27 silver badges50 bronze badges

What fixed it for me after I couldn’t scaffold IdentityFramework was by

  1. Checking VS2019 for updates.
  2. Update NuGet Packages (Tools -> Nuget Package Manager -> Manage NuGet packages for solution -> Click on the updates tab, select all and run update.
  3. Retry scaffolding identity

answered Jun 28, 2020 at 13:27

Joshua Tromp's user avatar

Cleaning the solution showed me an error of NuGet packages needed to be updated! I updated them and build the solution. Build Successful and I was able to create the controller class.

answered May 25, 2021 at 7:11

joekevinrayan96's user avatar

Trying to add MVC controller with views using EF for MVC project using Net5.0.

Using the following NuGet packages specific versions worked for me, while the problem was solved by using less version than the version of Microsoft.EntityFrameworkCore, for both Microsoft.EntityFrameworkCore.SqlServer and Microsoft.EntityFrameworkCore.Tools, these packages are referenced in the MVC project.

The correct packages are:

<ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="5.0.7" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.7" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.6" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.6">
           <PrivateAssets>all</PrivateAssets>
           <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
            </PackageReference>
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.7" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="5.0.2" />   
</ItemGroup>

answered Jun 18, 2021 at 1:39

Ashraf Sada's user avatar

Ashraf SadaAshraf Sada

4,3712 gold badges44 silver badges46 bronze badges

I also faced this same error when i was trying to scaffold identity template. I resolve this issue by updating nuget packages of the two major project of concerns(I mean the the two projects that has something to do with what i was to implement).

answered Jul 30, 2021 at 13:16

sammy Akinsoju's user avatar

I am also facing this issue.

Please follow this step,

  • Clean Your Solution
  • Open Nuget Manager
  • Check this version Microsoft.EntityFrameworkCore (I am using 5.0.8)
  • Check this version Microsoft.EntityFrameworkCore.Design (I am using 5.0.8)
  • Check this version Microsoft.EntityFrameworkCore.Tools (I am using 5.0.8)
  • Check this version Microsoft.EntityFrameworkCore.SqlServer (I am using 5.0.8)
  • Check this version Microsoft.VisualStudio.Web.CodeGeneration.Design (I am using 5.0.2)

Check this image also

  • After that Rebuild your solution and Create Scaffolding Controller

answered Aug 14, 2021 at 10:59

Abdulla Sirajudeen's user avatar

1

The problem is that you have some of the older versions of nuget pacakges installed in your project and when you try to scaffold the Asp.net core tries to install the latest packages which are required for scaffolding at this point Asp.net core throws such exception.

I suggest you to update your nuget packages and than try scafolding.

Wai Ha Lee's user avatar

Wai Ha Lee

8,41977 gold badges60 silver badges90 bronze badges

answered Sep 23, 2020 at 13:32

Mohammed Rehan Javed Abdul Kar's user avatar

I know that some of you might still facing the same issue,
I just did the next in VS 2022,

1- Checked the depencendies on the current project.
enter image description here

2- Remove all of them

3- Go to dependencies
add a lower version

enter image description here

and the clean the solution and add the views.

answered Aug 15, 2022 at 19:14

Jose Antonio's user avatar

1

I also faced the same issue, Here is How I solved the Issue

There was an error running the selected code generation, ‘Package restore failed. Rolling back package canges for web’

1— Check if your Solution has multiple projects, please check their Target Dot.net Framework.(in my case it was .Net Standard 1.6 for class libraries & .NetCoreApp 1.0 for Web Project, I changed it to .NetCoreApp 1.1)

2— After having the same framework, clean the web project, Rebuilt and Add new Controller.

If its successful fine otherwise You might encounter another error e.g

‘There was an error running the code generator: ‘No executable found matching command «dotnet-aspnet-codegenerator»‘

If you have project.json file open it other wise open .csproj.user project in note pad, please add following


Please note based on your .net version you might have different version no.

You may find instruction in ScaffoldingReadMe.txt file if its generated in your project

answered Aug 17, 2017 at 4:12

Aamir's user avatar

AamirAamir

68510 silver badges11 bronze badges

All I had to do was open the properties of my web project and change the TargetFramework from 2.1 to 2.2. Or to match whatever version of the framework your business and object layer are using.

answered May 30, 2019 at 14:22

BBoyd's user avatar

BBoydBBoyd

411 bronze badge

Had the same problem, but updating all the NuGet Packages has solved the problem.
Right click on <your project name> file -> Manage NuGet Packages -> Updates -> Select all packages -> Update

answered Apr 27, 2020 at 9:13

Maksym Voloshko's user avatar

I’m running .NET Core (and Entity Framework Core) 3.1.x.

I got this exact error and tried updating all the nuget packages and other relevant solutions already mentioned in the answers here.

The issue was simply that my database server was not running (it runs on a local VM). In other words, my database context (i.e. ApplicationDbContext) mentioned in the ‘Add Controller…’ window, was not able to access the db. Once I started the db server, my scaffolding created without issue.

Keep also in mind, the model/class (i.e. table) that the controller and views were referencing had not been created yet (I hadn’t run add-migration yet). So, it just needed the db connection only.

It’s kind of a silly (obvious?) solution, but very misleading when looking at the ‘Package Restore Failed’ error message.

answered Jun 9, 2020 at 15:56

Sum None's user avatar

Sum NoneSum None

1,9732 gold badges23 silver badges31 bronze badges

I had a similar issue with entity framework core sqlite nuget packages. I installed sqlite and sqlite core packages fixed this. Probably a needy package is missing. Also make sure SQL Server and Server Agent are running. Check those on SQL Server Configuration > SQL Server Services > Right click on SQL Server or Server Agent and start the service then restart the server. Guess this might help someone

answered Aug 11, 2020 at 7:32

FF new's user avatar

FF newFF new

1031 gold badge1 silver badge11 bronze badges

My solution
-Vs2019 all nuget packages upgrade

answered Sep 21, 2020 at 21:21

wasdoska's user avatar

As someone mentioned earlier, I updated all NuGet packages from Tools->Nuget Package Manager -> Manage NuGet Packages for Solution -> Updates tab -> Update All. I was then able to add a controller with EF and have VS generate the associated views.

answered Oct 13, 2020 at 13:40

Phillip's user avatar

Just update all Nuget Packages , Clean Solution and the rebuild solution. It solve the issues for me.

answered Jan 30, 2021 at 15:26

vsharma10286's user avatar

I just updated EntityFrameworkCore from Version 3.1.10 to 3.1.13 and it solved the problem. My Project file looks like:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.13" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="3.1.13" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.13" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.13">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.5" />
  </ItemGroup>

</Project>

answered May 3, 2021 at 6:59

Rahim's user avatar

RahimRahim

7796 silver badges6 bronze badges

I had this same issue when creating a new ‘Identity’ scaffolded item.
I managed to get this working by removing everything within the <ItemGroup> tags within the csproj file and running the code generator. The generator then installs packages that it needs.

answered May 22, 2021 at 10:27

Hannah's user avatar

HannahHannah

3315 silver badges8 bronze badges

In case you are using .net 5.0.14, downgrading every packages with version 5.0.14 from 5.0.14 to 5.0.12 fixed the problem for me.

answered Mar 10, 2022 at 7:15

KodFun's user avatar

KodFunKodFun

3033 silver badges8 bronze badges

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



Вообще, меня это жутко бесит, т. к. после глупого сообщения об ошибке совсем непонятно что делать дальше. Microsoft специально разработали установщик Windows Installer для расширения возможностей установки программ (в основном это касается системных администраторов), но не позаботились должным образом о безглючной работе этой службы или хотя бы об адекватных сообщениях о проблемах. А нам теперь это разгребать??

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

Ошибки msi файлов

«Error reading from file «имя файла» verify that the file exists and that you can access it» (Error 1305). Переводится «Ошибка чтения из файла … проверьте существует ли файл и имеете ли вы к нему доступ». Ну не тупняк ли? Естественно, что кнопка «Повторить» не помогает, а отмена прекращает всю установку. Сообщение особой смысловой нагрузки также не несёт, т. к. файл точно существует и я имею к нему доступ, иначе бы просто не смог его запустить и получить это сообщение, к тому же почему-то на английском языке??

А ошибка в том, что не Я должен иметь доступ к файлу, а установщик Windows, точнее сама Система. Решается очень просто:

Теперь ошибка установщика не появится! Можно добавить доступ на всю папку, из которой вы обычно инсталлируете программы, например на папку «Downloads», как у меня. Смотрим видео по решению проблем с правами доступа:

Ещё способы решить проблему

Описанный метод поможет при разных сообщениях, с разными номерами. Например, вы можете видеть такие ошибки файлов msi:

Во всех этих случаях должна помочь установка прав на файл и/или на некоторые системные папки. Проверьте, имеет ли доступ «система» к папке временных файлов (вы можете получать ошибку «Системе не удается открыть указанное устройство или файл»). Для этого:

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

Если служба Windows Installer всё равно не хочет работать, то проверьте права на папку «C:Config. Msi», сюда «система» также должна иметь полный доступ. В этом случае вы могли наблюдать ошибку «Error 1310». На всякий случай убедитесь, что к папке КУДА вы инсталлируете софт также есть все права.

Если вы используете шифрование папок, то отключите его для указанных мной папок. Дело в том, что хотя мы сами имеем к ним доступ, служба Microsoft Installer не может до них достучаться пока они зашифрованы.

Ещё ошибка может быть связана с битым файлом. Может быть он не полностью скачался или оказался битым уже на сервере. Попробуйте скачать его ещё раз оттуда же или лучше с другого места.

Ошибка установщика Windows

В случае общих проблем не будут устанавливаться никакие msi файлы, процесс установки, скорее всего, даже не начнётся. При этом могут появляться ошибки вида:

Или ещё нечто подобное со словами «ошибка msi», «Windows Installer Error». Всё это означает, что система дала сбой и теперь её надо лечить. Может вы ставили какой-то софт, который испортил системные файлы и реестр, или подхватили вирус. Конечно, никогда не будет лишним удалить вирусы, или убедиться что их нет. Но оставьте этот вариант на потом, т. к. обычно проблема кроется в другом.

Сначала давайте проверим работает ли служба Windows Installer:

Следующее что я посоветую сделать – это выполнить команду сканирования системы на повреждённые и изменённые системные файлы. Нажмите «Win + R» и введите

Sfc /scannow

Произойдёт поиск и замена испорченных файлов на оригинальные, при этом может потребоваться вставить установочный диск с Windows XP-7-10. После окончания процесса перегрузитесь и посмотрите, решена ли проблема.

Microsoft сам предлагает утилиту, призванную решить нашу проблему. Запустите программу Easy Fix и следуйте мастеру.

Параметры реестра и службы

Следующий способ устранения ошибки – восстановление рабочих параметров в реестре установщика Windows Installer.

Для этого скачайте архив и запустите оттуда два reg-файла, соответственно своей версии Windows. Согласитесь с импортом настроек.

В Windows XP или Windows Server 2000 установите последнюю версию установщика 4.5.

Если не помогло, то проделайте ещё перерегистрацию компонентов:

Если пишет, что не хватает прав, то нужно запускать командную строку от имени Администратора.

Если команды выполнились, но не помогло, то скачайте файл и запустите msi_error. bat из архива, проверьте результат.

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

Подведение итогов

Ошибки с установщиком Windows очень неприятные, их много и сразу непонятно куда копать. Одно ясно – система дала сбой и нужно восстанавливать её до рабочего состояния. Иногда ничего не помогает и приходится переустанавливать Windows. Однако не торопитесь это делать, попробуйте попросить помощи на этом форуме. В точности опишите вашу проблему, расскажите что вы уже делали, какие сообщения получили, и, возможно, вам помогут! Ведь мир не без добрых людей??

Ошибка при запуске приложения 0xc0000142 — как исправить

Многие пользователи, желая запустить какое-либо приложение или игру, могут столкнуться со всплывающем окном — “Ошибка при запуске приложения 0xc0000142”. Окошко с номером данной ошибки и сообщением «не может быть инициализировано приложение» может возникнуть в самый неподходящий момент, особенно это касается запуска игр и других программ, связанных с графикой.

В этой статье я разберу причины возникновения ошибки 0xc0000142, а также расскажу, как исправить 0xc0000142, предложив читателю различные варианты решения проблемы.

Что это за ошибка 0xc0000142

Стоп-ошибка с кодом “Ошибка при запуске приложения 0xc0000142” связана с нарушением структуры динамических библиотек (dll), потерей или повреждением какого-либо нужного системного файла, проблемами с совместимостью текущей версии ОС и требованиями запускаемой программы. Наиболее часто она возникает при запуске каких-либо игр и сторонних приложений (AutoCAD, Adobe Acrobat 9 Pro Extended, Trusted Desktop, LogonUI, Pes 2016, Mad Max и других).

Ошибка 0xc0000142 на английском

Почему появляется ошибка при запуске приложения 0xc0000142

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

Причина 1. Проблемы с совместимостью программы и текущей ОС

Если вы пользователь ОС Windows 7,8, 8.1. или выше, то ошибка 0xc0000142 при запуске игры может происходить по причине несовместимости текущей версии ОС и запускаемой программы.

Решение: Кликните правой клавишей мыши на иконке с игрой, выберите «Свойства», затем «Совместимость», нажмите на галочку в «Запустить программу в режиме совместимости с» и выберите вариант «Windows XP пакет обновления 3 (SP3)». Подтвердите изменения и запускайте игру. Если ошибка 0xc0000142 вновь возникает, попробуйте выбрать для совместимости другую версию ОС (Windows 95, XP, Vista и так далее).

Запустить программу в режиме совместимости с Windows 7

Причина 2. Запуск игры под учётной записью с минимальными правами

Недостаток прав используемой учётной записи может также вызывать ошибку при запуске приложения 0xc0000142.

Решение: Запускайте программу с административными правами (кликните правой клавишей мыши на иконку программы, а в появившемся меню выберите «Запуск от имени администратора»).

Причина 3. Неверное значение в системном реестре

Различные программы могут некорректно изменить значение ключа реестра.

Решение: нажмите комбинацию клавиш Win+R, в появившемся меню наберите regedit и нажмите ОК.

Наглядно можно посмотреть на этом видео:

Причина 4. Проблемы с DirectX и NET Framework

Повреждение (отсутствие) необходимых библиотек с пакетов DirectX и NET Framework могут вызывать ошибку инициализации приложения 0xc0000142.

Решение: Скачайте и установите свежие версии указанных приложений: DirectX и NET Framework.

Причина 5. Системные файлы повреждены вирусными программами

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

Решение: проверьте вашу систему мощным и заслуживающим доверий антивирусом (напр. Dr. Web CureIt!, Trojan Remover, AVG, 360 Total Security и др.), или воспользуйтесь онлайн-сканированием с помощью соответствующего сканнера (Eset Online Scanner и др.).

Проверка компьютера Dr. Web CureIt! на вирусы

Причина 6. Не установлены необходимые системные обновления

Часто ошибка при запуске приложения 0xc0000142 может возникать в случае отсутствия необходимых обновлений для версий ОС Windows 8/8.1 или других.

Решение: Скачайте и установите все обновления очереди центра обновлений.

Причина 7. Если повреждены системные файлы может появляться ошибка 0xc0000142

В случае повреждения файлов необходимой для правильной работы ОС Windows, система может выдать ошибку 0xc0000142.

Решение: Перезагрузите ПК в безопасный режим, от имени администратора нажмите комбинацию клавиш Win+R, в появившемся меню «Выполнить» наберите «sfc / scannow» (без кавычек), дождитесь окончания операции. Благодаря данной процедуре система проведёт проверку на различные ошибки и многие из них (включая ошибку 0xc0000142) будут устранены.

Также, можно воспользоваться инструментарием такой программы как CCleaner. Как это сделать смотрите в этом видео:

Причина 8. Сбои с временными файлами

Решение: Удалите все временные файлы с директории С:WindowsTemp.

Причина 9. Проблемы с драйверами к графическим картам

Иногда ошибка при открытии программы 0xc0000142 может происходить по причине повреждений драйверов к графическим картам (особенно это касается семейства карт Nvidia) или их моральном устаревании.

Решение: Скачайте и обновите драйвера к вашей графической карте Nvidia или Radeon.

Причина 10. Некорректная установка или работа загруженного извне приложения

Решение: Удалите, а потом заново установите требуемое приложение.

Причина 11. Повреждены системные файлы

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

Решение: Попробуйте вернуться к более ранней точке восстановления системы, когда ошибка при запуске программы 0xc0000142 не наблюдалась.

Причина 12. Аппаратные проблемы

Недостаток оперативной памяти, её аппаратная неисправность, неправильная настройка БИОСа, повреждение кластеров жёсткого диска и неверное напряжение от блока питания могут вызывать возникновение ошибки 0xc0000142.

Решение: Установите дополнительную планку памяти, проверьте работоспособность памяти с помощью специальных тест программ (напр., Memtest). Проверьте кластера своего винчестера с помощью системных средств сканирования жёсткого диска (кликните правой клавишей мыши на диск, затем выберите Свойства – Сервис — Выполнить проверку). Проверьте выходящее напряжение вашего БП тестером или обратитесь за этим к компетентному специалисту.

Заключение

Как видим, ошибка при запуске приложения 0xc0000142 может возникать по множеству причин, и с каждой из них нужно работать индивидуально. Тем не менее, следуя указанным мною советам можно очень быстро решить данную проблему, продолжив наслаждаться надёжностью и стабильностью работы вашего ПК.

Исправляем ошибку с кодом «0xc0000005» на Windows 10

Как правило, при возникновении ошибки, вы получаете следующее сообщение:

Произошла ошибка приложения и генерируется журнал ошибок. Исключение: нарушение прав доступа (0xc000000), Адрес.

Это сообщение появляется после попытки запустить в Windows любого приложения. После закрытия окна об ошибке, быстрее всего, у вас сработает блокировка на запуск этого приложения.

Код ошибки 0xc0000005 может проскакивать и в других сообщениях об ошибках, все зависит от того, какое приложение вы пытаетесь установить или запустить. Эта ошибка может появляться во время использования встроенных инструментов операционной системы, например дефрагментация диска.

Причины появления этой ошибки многочисленны. Однако наиболее распространенные причины это:

Иногда эту ошибку 0xc0000005 может вызывать так же неправильно установленные обновления безопасности для Windows.

Как ещё можно исправить 0xc0000005

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

В других случаях останется только откатить систему к более раннему состоянию с помощью точки восстановления. Если данный способ реализовать невозможно, то поможет переустановка Windows. Это самое последнее, что можно сделать.

Удалось ли устранить ошибку 0xc0000005 с помощью советов из статьи?

Исправление ошибки при помощи антивируса

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

Бывает и так, что антивирусное программное обеспечение блокирует попытки запуска некоторого софта, так как считает его потенциально опасным. Проверьте раздел «Карантин», если найдёте там искомый объект, добавьте его в белый список для возобновления доступа.

Способ № 2: Отладка через утилиту «Выполнить»

Для того чтобы справиться с ошибкой 0xc0000005 в программке «Выполнить», действовать нам придется так:

Если ошибка 0xc0000005 больше не беспокоит, преспокойненько идем пить чай: проблема решена. Если же Windows все так же ведет свою маленькую забастовку, повторно открываем утилиту «Выполнить» и продолжаем отладку, используя другие команды:

При этом не забываем перезагружать и в дальнейшем проверять на работоспособность Windows после каждой выполненной задачи. Так или иначе, результат таких действий не заставит себя долго ждать – ошибка 0xc0000005 исчезнет из системы неотлагательно.

Ошибка 5 отказано в доступе Windows 10

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

Решить подобную проблему возможно следующим образом:

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

Для разрешения доступа к папке всем пользователям, необходимо выполнить следующие действия:

Аналогичная процедура делается с такими параметрами, как «Администраторы», «Пользователи», «Система», «TrustedInstaller».

Следует учесть момент, что если операционная система английская, то писать нужно не «Админ», а «Administrator». После этого следует быть нажата клавиша «Enter». Следующим этапом станет написание: net localgroup Администраторы /add localservice. (Administrators). В конце процедуры необходимо закрыть окно и выполнить перезагрузку компьютера. Если всё было сделано без ошибок, то Windows 10 код ошибки 5 больше не появится.

Способ № 1: Редактирование раздела «Программы и компоненты»

Стоит заметить, что чаще всего сообщение об ошибке 0xc0000005 появляется после очередного обновления Windows 7. Причем от пользователей здесь мало, что зависит. Спровоцировать подобную системную неполадку может установка таких абсолютно безопасных с виду пакетов обновления, как KB2859537, KB971033, KB2872339 и KB2882822.
На одних компьютерах они нормально приживаются в системе, а на других – неизменно приводят к сбоям. В таком случае достаточно будет удалить эти обновления из системы, чтобы устранить на ПК ошибку 0xc0000005. А сделать это можно так:

После этого останется только перезагрузить Windows. В итоге же при новом запуске компьютера ошибка 0xc0000005 исчезнет. Правда, стоит заметить, что способ этот весьма утомительный. Почему? Потому что необходимые значения зачастую приходится искать в списке обновлений, состоящем из 100, а то и 200 строчек. Не очень удобно, согласитесь? В таком случае сэкономить и время, и нервы проще выполнить настройку системы с помощью утилиты «Выполнить».

Откат ОС до точки восстановления

Из-за разнообразия причин, в связи с которыми появляется ошибка 0xc0000005 при запуске утилит и игр, может случиться так, что она не пропадёт после деинсталляции того или иного апдейта. В таком случае, поможет откат OS до того момента, когда всё функционировало правильно. Постарайтесь вспомнить, когда начались беды с неправильным стартом ПО и вернитесь к дате исправной работы устройства.

Попробуйте восстановление системных файлов при помощи инструментов dism и sfc

Способ № 4: Восстановление системы

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

Как будем действовать? Для начала входим в раздел «Восстановление системы». Сделать это можно разными способами:

В принципе какой способ ни выбери, план дальнейших действий все равно будет тем же самым. Так, после запуска программки для начала жмем кнопку «Далее», а далее выбираем из предложенного перечня необходимую точку восстановления – ту, которая по времени идет раньше установки обновления. Затем для продолжения восстановления параметров системы вновь нажимаем «Далее»:

После этого проверяем введенные данные и, если все правильно, нажимаем кнопку «Готово», дабы запустить процесс восстановления системы:

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

Views : 7553

Не запускаются новые игры

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

Теперь вы знаете, что делать, если игра не запускается. Каждый случай несет индивидуальный характер и возможно описанные методы не помогут. Есть свое решение? Пишите в комментарии, ваш опыт может помочь другим пользователям решить проблему.
Лучшее «Спасибо» — ваш репост

Способ № 3: Настройка посредством работы в командной строке

Очистить список обновления Windows от ошибочных компонентов можно также в командной строке. Для этого запускаем ее одним из известных нам способов (детальнее о них здесь), а затем поочередно вбиваем в нее команды, указанные в способе № 2:

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

Причина возникновения

«Ошибка при запуске приложения 0xc0000005» значит, что произошёл сбой при инициализации программных компонентов и зачастую она является следствием системных обновлений. Текст сообщения может отличаться, но код будет неизменен, иногда также возможно зависание ОС и появление синего «экрана смерти». Так, после установки новых пакетов на «Семёрке» вместо улучшения работы нередко появляется сбой при запуске игры или программы. В 10 версии Windows причины, провоцирующие ошибку, другие и проблему предстоит решать уже иными способами. Часто помогает удаление или остановка работы антивируса, но возможны также проблемы с памятью RAM, так что нужно будет выполнить сканирование с помощью специальной утилиты. Основные причины, вызывающие ошибку (код исключения) 0xc0000005 на Windows 10, 8, 7:

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

Источники:

Https://it-like. ru/ne-rabotaet-ustanovshhik-windows-installer-oshibka-msi/

Https://droidov. com/oshibka-pri-zapuske-prilozheniya-0xc0000142-kak-ispravit

Https://mycomp. su/operacionka/oshibka-pri. html

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

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

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

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

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

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

enter image description here

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

enter image description here

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

enter image description here

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

enter image description here

Ошибка:

enter image description here

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

Обновление:

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

20 ответов

Лучший ответ

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

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

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


75

VSB
4 Мар 2020 в 08:45

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


0

SkinnyPete63
27 Июл 2020 в 10:27

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

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

    [NotMapped]
    [Display(Name = "Image")]
    public HttpPostedFileBase ImageUpload { get; set; }


    [NotMapped]
    [Display(Name = "Valid from")]
    public Nullable<DateTime> Valid { get; set; }


    [NotMapped]
    [Display(Name = "Expires")]
    public Nullable<DateTime> Expires { get; set; }

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

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

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


0

Rusty Nail
19 Мар 2019 в 20:55

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

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


1

sGermosen
29 Сен 2017 в 11:59

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


0

Hoodlum
18 Дек 2019 в 20:11

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

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

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

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

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

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

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

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


0

IfElseTryCatch
31 Авг 2018 в 13:58

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


0

Leonid
15 Июн 2017 в 14:51

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


0

Adam Hey
16 Дек 2019 в 16:54

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


0

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

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


0

Exel Gamboa
16 Окт 2019 в 02:58

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


0

Sajithd
19 Сен 2019 в 04:12

C:Users{WindowsUser}AppDataLocalMicrosoftVisualStudio16.0_8183e7d1ComponentModelCache

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


0

Farzad Sepehr
30 Авг 2019 в 17:01

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

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


0

user3416682
28 Авг 2018 в 21:56

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


0

Oleksandr Kyselov
21 Авг 2018 в 08:45

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

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

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

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

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

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


0

Deepak Savani
28 Май 2018 в 20:04

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

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

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

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


5

Maksym Labutin
23 Дек 2019 в 08:18

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

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

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


13

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

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


0

Kurkula
21 Мар 2018 в 18:00

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


0

Icementhols
18 Май 2019 в 17:04

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

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

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


2

MOHAMMAD OMAR
19 Ноя 2019 в 12:36

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 badges96 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 badges96 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 badges96 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 badges96 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 badges96 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 badges96 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,58318 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. Показов 7650. Ответов 8

Метки asp .net core, c#, entity framework core, visual studio 2019, visual studio (Все метки)


Проект ASP NET CORE 3, использую EF Core 3.1.13.

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

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

Про гуглил данную ошибку и все пишут про отсутствия нужных пакетов и советуют через Nuget установить их. Пакеты, которые перечислялись у меня все в файле csproj есть:

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

954 / 582 / 202

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

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

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

954 / 582 / 202

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

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

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

I am having a problem following the tutorial exactly as written. When I try to add a Razor page as instructed…

Complete the Add Razor Pages using Entity Framework (CRUD) dialog:

In the Model class drop down, select Movie (RazorPagesMovie.Models).
In the Data context class row, select the + (plus) sign and accept the generated name RazorPagesMovie.Models.RazorPagesMovieContext.
In the Data context class drop down, select RazorPagesMovie.Models.RazorPagesMovieContext
Select Add.

I get an error that says… ‘There was an error running the selected code generator: The entity type ‘Program’ requires a primary key to be defined.’

I am using Microsoft Visual Studio Community 2017. Version 15.8.5


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

  • ID: 6719f08e-3bd7-dc1a-71df-f2ef9fbca9d8
  • Version Independent ID: 7096fdb3-612e-9e00-bd0b-8ea4886a09ce
  • Content: Add a model to a Razor Pages app in ASP.NET Core
  • Content Source: aspnetcore/tutorials/razor-pages/model.md
  • Product: aspnet-core
  • GitHub Login: @Rick-Anderson
  • Microsoft Alias: riande

I am having a problem following the tutorial exactly as written. When I try to add a Razor page as instructed…

Complete the Add Razor Pages using Entity Framework (CRUD) dialog:

In the Model class drop down, select Movie (RazorPagesMovie.Models).
In the Data context class row, select the + (plus) sign and accept the generated name RazorPagesMovie.Models.RazorPagesMovieContext.
In the Data context class drop down, select RazorPagesMovie.Models.RazorPagesMovieContext
Select Add.

I get an error that says… ‘There was an error running the selected code generator: The entity type ‘Program’ requires a primary key to be defined.’

I am using Microsoft Visual Studio Community 2017. Version 15.8.5


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

  • ID: 6719f08e-3bd7-dc1a-71df-f2ef9fbca9d8
  • Version Independent ID: 7096fdb3-612e-9e00-bd0b-8ea4886a09ce
  • Content: Add a model to a Razor Pages app in ASP.NET Core
  • Content Source: aspnetcore/tutorials/razor-pages/model.md
  • Product: aspnet-core
  • GitHub Login: @Rick-Anderson
  • Microsoft Alias: riande

Произошла ошибка при запуске выбранного генератора кода: «Ссылка на объект не установлена для экземпляра объекта». Ошибка?

Изображение 86770

Я испробовал все решения, такие как ремонт VS 2013, но бесполезно. Когда вы создаете контроллер, щелкая правой кнопкой мыши на папке Controller и добавляете контроллер, затем вы щелкаете правой кнопкой мыши в Action недавно созданного контроллера и выбираете Add View, это происходит именно тогда, когда я пытаюсь создать представление. Это не новый проект, это существующий проект.

24 авг. 2016, в 17:24

Поделиться

Источник

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

Ricardo Silva
13 март 2018, в 17:47

Поделиться

Для меня ошибка связана с тем, что у меня был проект в моем решении, который был библиотекой проектов .NET Core и упоминался в проекте, в котором размещался DbContext.

Удаление — или, я думаю, изменение типа — в основной библиотеке .NET была устранена проблема

Timo Hermans
11 июнь 2017, в 14:05

Поделиться

У меня была эта проблема на моем VS2017, и я решил ее, выполнив это:
Перейдите в C:UsersusernameAppDataLocalMicrosoftVisualStudio15.0_7fca0c70 и вы увидите папку с именем ComponentModelCache только что переименованную в _ComponentModelCache или что-то еще, Visual Studio снова создаст эту папку.
Под именем папки VisualStudio 15.0_7fca0c70 можно заметить, что это зависит от версии VS. Теперь вы готовы идти. Надеюсь, это кому-нибудь поможет.

Mohit Lohani
10 апр. 2019, в 07:04

Поделиться

Просто измените вашу ConnectionString в файле Web.Config От

<add name="xxx" connectionString="Data Source=xxx;initial catalog=xxx;Persist Security Info=True;User ID=xxxx;Password=xxxx;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />

к

<add name="xxx" connectionString="metadata=res://*/EFMOdel.csdl|res://*/EFMOdel.ssdl|res://*/EFMOdel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=xxxx;initial catalog=xxxx;persist security info=True;user id=xxxx;password=xxx;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />

ghanshyam shah
23 окт. 2018, в 01:00

Поделиться

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

Amantle Mashele
25 сен. 2018, в 10:07

Поделиться

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

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

Opsimath
18 май 2018, в 18:28

Поделиться

Эта ошибка связана с моделью данных платформы Entity.
для решения Выполнение этих шагов…

  • Удалите модель данных Entity Framework.
  • Снова регенерировать модель из проекта базы данных.
  • затем переделайте решение… и наслаждайтесь кодированием.

Umer Ashiq
19 апр. 2017, в 12:46

Поделиться

У меня такая же ошибка в vs2017 на windows10, пожалуйста, попробуйте запустить vs от имени администратора, надеюсь, это будет работать и для вас.

Frank
19 апр. 2019, в 03:28

Поделиться

Перезапустите Visual Studio и попробуйте снова.

Shadi Namrouti
14 апр. 2019, в 15:01

Поделиться

Ещё вопросы

  • 0Перезагрузите вкладки в angularjs
  • 1Android: создание обработчика в TimerTask внутри службы
  • 1Восстановление базы данных SQL Server из снимка в C #
  • 1Объедините два нажатия кнопки селена в if if
  • 1RadioButtonList Выбор конкретного индекса
  • 0jQuery append — html wrote не вызывает другие события
  • 0JavaScript с использованием DOM и изменение цвета
  • 0Как выбрать строки, которые имеют все значения в коллекции идентификаторов
  • 0Сохранение состояния меню после перезагрузки страницы
  • 1Невозможно привести .SelectedItems из выпуска DataGrid
  • 0ошибка: переопределение класса TextDocsCmpr
  • 0jQuery всплывающая ошибка для подписки на комментарии
  • 0Установить значение по умолчанию выбрать базу данных формы AngularJS
  • 1Воспроизведение кодированного пользовательского интерфейса из консольного проекта при воспроизведении. Функция Initialize () вызывает исключение System.TypeInitialization.
  • 1Как использовать изображение в ListView из базы данных в Android?
  • 0Angularjs — ошибка: $ location и $ anchorScroll для прокрутки вызова 2 раза на мой контроллер
  • 1Как заставить класс использовать метод получения / установки по умолчанию, когда на него ссылаются непосредственно в C #?
  • 0Общая архитектура InterlockedIncrement для 32/64-битных
  • 0Как вставить значение эха в переменную? [Дубликат]
  • 0Дескрипторы для Pointclouds
  • 1Добавление слушателей в Netbeans
  • 0QTableView, выберите и Shift + клик
  • 1Наследование объектов в protobuf-сети
  • 0Граф с Join в MySQL
  • 0.query () отображает неверный путь
  • 0я должен установить все базы данных charset utf8_general_ci
  • 1Отсутствует @using при просмотре бритвы
  • 0Разбор строки массива массива строк обратно в массив
  • 1Улучшение производительности вложенного цикла for в node.js
  • 1VueJs — DOM не обновляется при мутации массива
  • 0Как обновить HTML-контент, когда я выполняю процесс в предложении, в то время как с JavaScript
  • 1Хэшированное значение регулярное выражение
  • 0Как разрешить внешний символ
  • 0jQuery Mobile настройки Иконки для кнопок
  • 0Как загрузить и вставить несколько изображений в PHP?
  • 0Угловая нг-сетка отключает автоматическую генерацию столбцов
  • 0C # взаимодействие с CUDA C dll — избыточный
  • 1Разбор пустого тега с ElementTree
  • 1Прочитайте zip-файлы из amazon s3, используя boto3 и python
  • 1Правильный способ сократить код с помощью множества приведений и очевидных шаблонов в C #
  • 0JQuery не работает должным образом на mouseenter и mouseleave
  • 0Как использовать форматтер / парсеры директивы ngModel в пользовательской директиве?
  • 0Ошибка запроса данных PHP с объектом / строкой, теперь конструкция SQLite3
  • 0Создайте триггер ежегодно в MySQL
  • 0Найти точный дубликат по полю таблицы соединений
  • 1Selenium webdriver element.click () не работает должным образом (chrome, mocha)
  • 1Является ли RCW (Runtime Callable Wrapper) единственным способом вызова неуправляемого com-объекта в .net?
  • 0Войти и оплатить с помощью интеграции с Amazon
  • 1Как я могу использовать плагин ServiceStack RegistrationFeature с Redis?
  • 1использовать список объектов из формы один в форме два

Сообщество Overcoder

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • При запуске starbound вылетает ошибка
  • При запуске компьютера ошибка cpu fan error