Assets file obj\project.assets.json doesn't have a target - VS2017 - c#

Using Visual Studio 2017, AspNetCore 1.1.2
All of a sudden I am getting following error when I am trying to publish (Release build) any project in the solution:
Assets file 'C:\example\obj\project.assets.json' doesn't have a target for
'.NETFramework,Version=v4.5.2/win7-x86'. Ensure that restore has run
and that you have included 'net452' in the TargetFrameworks for your
project. You may also need to include 'win7-x86' in your project's
RuntimeIdentifiers.
Have checked in the project.assets.json files, I have:
"targets": {
".NETFramework,Version=v4.5.2": {
and
"runtimes": {
"win7-x86": {
"#import": []
}
In the *.csproj files I have:
<PropertyGroup>
<TargetFramework>net452</TargetFramework>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
Have made no changes to config in the projects. Only thing is that I have updated VS2017 to latest version today, 15.6.3. Could this cause issue?

According to the Microsoft blog (which, bizarrely, my account doesn't have permissions to post in), this isn't a bug, and is entirely caused by ReSharper. If you disable this, the problem goes away.
Errr, one problem: I'm getting this error, and I don't have ReSharper.
After a lot of hunting around, I found the reason I was getting the error on my .NET Core project which had been upgraded from 1.0 to 2.1.
When running my project in Debug or Release mode, everything worked fine, but when I tried to publish to Azure, I got that error:
Assets file '(mikesproject)\obj\project.assets.json' doesn't have a target for '.NETCoreApp,Version=v2.0'. Ensure that restore has run and that you have included 'netcoreapp2.0' in the TargetFrameworks for your project.
Although I had updated the version of .NET Core to 2.1 in Project\Properties and upgraded the various nuget packages, there was one place which hadn't picked up this change... the Publish Profile file.
I needed to go into the Properties\PublishProfiles folder in my solution, open up the .pubxml file relating to the way I was publishing to Azure, and change this setting from netcoreapp2.0 to netcoreapp2.1:
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
. . .
<TargetFramework>netcoreapp2.0</TargetFramework>
. . .
</PropertyGroup>
</Project>
Ridiculous, hey?
I do wish Microsoft error messages gave some clue as to the source of problems like this.

Restarting Visual Studio solved the error for me.

Right click on the project file, and click unload. Then right click on the project and reload.

Had this error in similar situation. This has helped me: Link
This is my property group in *.csproj file of my .net core 3.0 project:
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>netcoreapp3.0</TargetFrameworks>
<RuntimeIdentifier>win-x64</RuntimeIdentifier> <----- SOLVES IT. Mandatory Line
</PropertyGroup>

Migrating from nuget 5.4 to nuget 5.8 solve the problem on my devops build server

Delete the publish profile you created and create a new one. The wizard will put in the correct targetframe work for you and publish again. It should solve the problem.

If your build script starts with a dotnet restore and ends with a dotnet publish --no-restore, you must make sure that they both include the same --runtime parameter.

Restarting Visual Studio or unloading/reloading the project didn't work for me, but deleting the "obj" folder and then rebuilding seems to have fixed the issue.

For me the problem ended up being that one of my NuGet feeds was down, so a package was not getting updated properly. It wasn't until I ran a NuGet package restore directly on the solution that I saw any error messages related to my NuGet feed being down.

You should try all the other solutions here first. Failing that you can try what eventually unblocked me when none of these did. I ran into this problem when porting a Jenkins build to an Azure DevOps pipeline on a pool of agents. It took about 60 builds before I tried every other possibility. I found out that needed to do two things:
Ensure the tooling was consistent for this specific project
Use a nuget restore friendly with the version of MSBuild used after finding out that mattered yet I couldn't use the proposed workaround for just updated nuget tooling.
The versions I needed to use are likely different than yours.
1:
call choco install windows-adk-all --version=10.0.15063.0 --force
call choco install windows-sdk-10.1 --version=10.1.15063.468 --force
2:
call MSBuild -t:restore Solution.sln
call MSBuild Solution.sln /t:rebuild;pack /p:Configuration=Release /p:Platform="Any CPU"

I got this error when upgrading a web project from netcoreapp3.1 to net5.0.
One of the answers here pointed me in the right direction:
The publish profile still had netcoreapp3.1 as target framework. Edited the publish profile and changed target framework to net5.0 and it worked.
(Visual Studio 16.8)

For me it was the happening because I had migrated my project from .net5.0 to .net6.0 and the problem was caused when I was publishing the project while debugging worked fine.
Checking the publishing profile showed that it had a configuration for .net5.0 in it:
Changing the existing .net core version with the desired one resolved the issue:
Or you can directly change it by going into the publishing profile .pubxml file under Properties > PublishingProfiles directory.

To me, the error was caused because of an existing global.json file in the solution level folder, pointing to a different .NET version.
Removing that file (or changing its SDK version) resolved the problem

Upgrading NuGet version from 5.5.1 to 5.8.0 fixed the issue.

I had similar issue, when I installed a new sdk version.
Exception was:
Severity Code Description Project File Line Suppression State Error NETSDK1005
Assets file '.. \RazorPages\obj\project.assets.json' doesn't have a target for
'netcoreapp3.1'. Ensure that restore has run and that you have included 'netcoreapp3.1'
in the TargetFrameworks for your project. RazorPages
C:\Program Files\dotnet\sdk\5.0.102\Sdks\Microsoft.NET.Sdk
\targets\Microsoft.PackageDependencyResolution.targets 241
Solution was to select again the target version of the project.
right click on solution
Properties\Application Tab
Change Target framework version to something different and change it back.

Running dotnet restore --packages .nuget in the project directory fixed the issues for me.

A colleague ran into this after upgrading an application from dotnet core 1.1 to dotnet core 2.1. He properly updated all the targetFramework references within the various csproj files, and had no issues on his local development machine. However, we run Azure DevOps Server and build agents on-premises, so the build agent was reporting this error after a pull request build was executed.
The dotnet clean task was throwing an error because of the new targeted framework. dotnet clean uses the same targets as build, publish, etc, so after a change in target frameworks the dotnet restore must happen before the dotnet clean to update the dependent files. In hindsight this makes sense because you want to restore dependencies to the proper target framework before you do any building or deploying.
This may only affect projects with upgraded target frameworks but I have not tested it.

Receiving similar error for 'netcoreapp3.1' when building using command line. It turned out to be an MsBuild switch that caused the issue. Specifically speaking:
/p:TargetFramework="netcoreapp3.1"
Removed the switch and the error was fixed.

In my case updating visual studio 2019 to the latest version, fixed the issue.

In my case, if you have TargetFrameworks and TargetFramework together in the csrpoj file, remove TargetFramework will solve the problem.
edit it from:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard2.0;net461;</TargetFrameworks>
<TargetFramework>net461</TargetFramework><!--remove this line-->
</PropertyGroup>
</Project>
to
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard2.0;net461;</TargetFrameworks>
</PropertyGroup>
</Project>

From my experience if you have dependencies in your solution built using "ProjectSection(ProjectDependencies) = postProject"
then in this case dotnet build goes nuts.

I ran into the NETSDK1047 when playing around with Docker in a brand new dotnet project created using dotnet new worker and the docker file from dotnet-docker samples.
❯ docker build -t dockertest .
output elided...
/usr/share/dotnet/sdk/6.0.300/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(267,5): error NETSDK1047: Assets file '/source/obj/project.assets.json' doesn't have a target for 'net6.0/linux-musl-x64'. Ensure that restore has run and that you have included 'net6.0' in the TargetFrameworks for your project. You may also need to include 'linux-musl-x64' in your project's RuntimeIdentifiers. [/source/dockertest.csproj]
The command '/bin/sh -c dotnet publish -c release -o /app -r linux-musl-x64 --self-contained true --no-restore /p:PublishTrimmed=true /p:PublishReadyToRun=true /p:PublishSingleFile=true' returned a non-zero code: 1
dockertest on  main [✘] via .NET v6.0.202 🎯 net6.0
❯
The issue was because I forgot to add a .dockerignore file ignoring the bin and obj directories.
I only realized why because I tried different Dockerfiles from the dotnet-docker repo and got a different error which has this same resolution. I'll try to make a PR to the docs of NETSDK1047 to add this resolution. edit: link to PR https://github.com/dotnet/docs/pull/29530

Had the same problem, for me it was that I had a space before my TargetFramework
<TargetFramework> net6.0</TargetFramework>

I upgraded from netstandard to net6.0, when publishing had to change TargetFramework to net6.0

On my end I had this issue with net6.0 at build time, even before trying to publish. Even if everything was pointing to csproj and it had all the right TargetFramework, the issue was that our repo had a Nuget.Config at it's root and it included a configuration for a local disk Nuget Repo of another programmer. I disabled the Nuget.Config file and I was able to build the project. It was probably unable to restore the Nuget Packages but the error message was misleading.

clean cache and restart VS then it worked for me.

Related

Publish error: Found multiple publish output files with the same relative path

When I publish my ABP project I get the following error:
C:\Program Files\dotnet\sdk\6.0.100-rc.1.21458.32\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.ConflictResolution.targets(112,5): error NETSDK1152: Found multiple publish output files with the same relative path:
D:\Github\volo\abp\lepton-theme\src\Volo.Abp.AspNetCore.Mvc.UI.Theme.Lepton\compilerconfig.json,
D:\Github\volo\abp\bookstore\src\Acme.BookStore.Theme\compilerconfig.json,
D:\Github\volo\abp\lepton-theme\src\Volo.Abp.AspNetCore.Mvc.UI.Theme.Lepton\package.json,
D:\Github\volo\abp\bookstore\src\Acme.BookStore.Web\package.json.
D:\Github\volo\abp\bookstore\src\Acme.BookStore.Web\Acme.BookStore.Web.csproj
Issue:
The issue raises after .NET 6 migration.
There's a new feature that blocks multiple files from being copied to the same target directory with the same file name.
See https://learn.microsoft.com/en-us/dotnet/core/compatibility/sdk/6.0/duplicate-files-in-output
Solution #1 (workaround):
You can add the following build property to all your publishable (*.Web) projects' *.csproj files.
This property will bypass this check and works as previously, in .NET5.
<PropertyGroup>
<ErrorOnDuplicatePublishOutputFiles>false</ErrorOnDuplicatePublishOutputFiles>
</PropertyGroup>
Solution #2:
Exclude the problematic files to be copied to the output folder.
In this example we'll exclude these files: compilerconfig.json and package.json.
Add the following lines to your common.props (located in the root directory of your solution):
<Content Remove="compilerconfig.json;package.json"/>
<None Include="compilerconfig.json;package.json">
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>
The above answers led me to my solution. My case is a self-building Entity Framework library project that was now copying over its appsettings.json when building the website that used it.
My solution was to let it copy to output folder (when I am doing migration actions in VS**) but prevent it from publishing using the "Never" value because it is only ever published as a library under a website or web service.
<ItemGroup>
<Content Include="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</Content>
</ItemGroup>
** My EF library project builds itself according to the pattern in this data-seeding article.
Thus do I eat my cake and keep it.
If you are getting this in a azure devops pipleline you can add the following task to specify the SDK version for your build
- task: UseDotNet#2
displayName: 'Install .Net SDK version'
inputs:
packageType: sdk
version: x.x.xxx //example (3.1.416)
installationPath: $(Agent.ToolsDirectory)/dotnet
https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/tool/dotnet-core-tool-installer?view=azure-devops
I ran into this with a Blazor WebAssembly project and an associated integration test project which both had appsettings.json files while I was dotnet publish'ing out via a GitHub action. I found two additional ways that worked for me (along with the accepted answer):
Add <IsPublishable>false</IsPublishable > to the test project
In the dotnet publish commands, specify the .csproj directly via arguments
I ran into this issue with a web application that had a Razor Class Library. The culprit file was LIBMAN.JSON.
Right click on the file and change the properties of the file to:
Build Action: NONE
Copy to Output Directory: DO NOT COPY
Other files that are used for tooling only could possibly be changes the same way.
This is caused by a breaking change in the .NET 6 SDK, and is independent of the .NET version your projects target. For example if you install Visual Studio 2022 it will install the .NET 6 SDK and use that for builds and deploys.
You can force VS to use an older SDK toolchain by generating a global.json file by running dotnet new globaljson in your solution root, then replacing the "version" property value with the desired SDK version (use dotnet --list-sdks to list installed versions).
I guess this means if you have a project dependency A->B where A and B are both executable and have their own appsettings.json, it would be preferable to split project B into B1 as a shell project with the appsettings.json and B2 as a library with all of B's functionality. Then dependencies A->B2 and B1->B2 would avoid the "multiple publish output files" issue.
I have also used compilerconfig.json for compiling scss to css.
And the easiest fix through UI is to:
Open Solution Explorer->compilerconfig.json->right click->properties
and there set:
Build Action: None
Copy to Output Directory: Do not copy
Do this for all compiler.config files (in my case on client project as well as on the server)
The reason behind this is that this compiler config is only used locally in building process but it is not required later on while app is running.
If your projects (All part of the same solution) uses a different version of the same nuget pacage, you will see this error. Now you can either find a workaround as others mentioned in the answers if for some reason you have to keep both versions (which is not a good practice).
Or do the right thing and make sure all project using same version of the package. to do that just open Visual studio's NuGet package manager for solution as shown in the screenshot
A window opens which will have a consolidate tab at the top, click on the consolidate tab. if you have a version conflict, you will be able to see lisr=t of NuGet packages on the left side. If that is the case it means you have conflicts. Click on any package and you will be able to see the list of your solution's projects on the right side just like the following screenshot
in my example (screenshot), I have 2 versions of Microsoft.Net.Sdk.Functions
one with 3.0.13 and 3.0.11.
All you need to do is to select your preferred version and click install and both projects will be updated to the same version.
Push the changes and devops build again and enjoy
I have two projects, API and Hangfire.
The duplication was in publishing hangfire since it uses both API and Hangfire projects and I solved it by removing appsettings files before the publish step.
COPY . .
RUN find ${API} -iname "appsettings*.json" -exec rm {} \;
RUN dotnet publish ${HANGFIRE}/*.csproj --configuration Release --output out --no-restore
I was able to resolve it by setting the Microsoft.NET.ConflictResolution.targets file under the <NETSdkError Condition="'$(_ResolvedFileToPublishContainsDuplicates)' == 'false'" <= this was originally true.
This file is located in "\Program Files\dotnet\sdk\6.0.100\Sdks\Microsoft.NET.Sdk\targets"

dotnet core::Unable to run your project. Ensure you have a runnable project type and ensure 'dotnet run' supports this project

I have been running into an error lately trying to run some code with dotnetcore. When I try to run the project in the console (dotnet run), I get this error.
Unable to run your project.
Ensure you have a runnable project type and ensure 'dotnet run' supports this project.
A runnable project should target a runnable TFM (for instance, netcoreapp2.0) and have OutputType 'Exe'.
The current OutputType is 'Exe'.
FYI, here are entries in the .csproj file
Also, I have the following skds and runtimes installed. Yet, whatever TargetFramework I set in the .csproj, I get the same error.
I found a solution to my issue.
The problem was that I had created the project using Visual studio. Hence, the .csproj project file was not in a suitable format for dotnet core.
To solve the issue, I created an empty project with dotnet core:
mkdir myNewApp
cd myNewApp
dotnet new console
Then, I added to the project all the source files I had created with visual studio by simply copying and pasting them in the app folder. I grouped them in the single directory 'src'. At build, dotnet core automatically finds these files and builds the project with them.
Mine is an Azure Durable function. I got the following error when I try to run it with dotnet cli using the command dotnet run.
Unable to run your project.
Ensure you have a runnable project type and ensure 'dotnet run' supports this project.
A runnable project should target a runnable TFM (for instance, net5.0) and have OutputType 'Exe'.
The current OutputType is 'Library'.
The solution is simple. You cannot use dotnet cli for this. Instead You need to run using the command func start as explained here.
And of course you need to install the azure function tools.
Most probably it is do something with the version you are trying, in my case, I was using .nerstandard 2.0 which was wrong and I changed it to net5.0 and I was able to run successfully.
It looks like this now -
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
I have experienced the same problem that the project refuses to create an EXE file. It was showing to compile a DLL, yet required an EXE to run.
I was using dotnet core and VS-Code and didnt suspect anything until I tried to rename the project folder to start another with the same name. What I got was greyed out folder/file names for some time about 10 sec with no name change.
Only then I realized: though I deleted "bin" folder, there was an instance of the project somehow running alive but hidden (should have prevented me deleting folder otherwise) and prevents any new EXE to be written.
Solution you might ask, simple: just close/restart IDE completely. Any program spawned with it will be terminated. trying to close/terminate terminals do not work.
Open CMD.EXE and run the following commands:
dotnet new console -o myApp
cd myApp
dotnet run
It works for me.
https://dotnet.microsoft.com/learn/dotnet/hello-world-tutorial/run

Project does not reference framework except that it does

I have a solution which contains multiple projects.
All projects target v4.6.1 of the .NETFramework.
However when I build my solution and try to run it I get the following exception:
Your project does not reference ".NETFramework,Version=v4.6.1"
framework. Add a reference to ".NETFramework,Version=v4.6.1" in the
"TargetFrameworks" property of your project file and then re-run NuGet
restore.
Can anyone point me in the correct direction?
I don't see what is going wrong.
Config1:
<RootNamespace>Exact_Online_Database</RootNamespace>
<AssemblyName>Exact_Online_Database</AssemblyName>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
Config2:
<RootNamespace>ExactOnlineConsoleApp</RootNamespace>
<AssemblyName>ExactOnlineConsoleApp</AssemblyName>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
Config3:
<RootNamespace>Exact_Online_Services</RootNamespace>
<AssemblyName>Exact Online Services</AssemblyName>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
Config4:
<RootNamespace>Example</RootNamespace>
<AssemblyName>Example</AssemblyName>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
Deleting the obj folder resolved this issue for me as recommended in Henry He's answer to this question.
For info I came across this issue when I tried to build a project that had been changed to .NET Core (from Framework) on a different branch. When I switched back to a branch with the original framework project it would no longer build.
Did you recently change from an older version of Visual Studio to VS 2017 to build your solution? It appears that the build process is looking for the <TargetFrameworks> element, not the <TargetFrameworkVersion>.
Refer to the documentation here for more info.

Your project does not reference ".NETFramework,Version=v4.6.2" framework. Add a reference to ".NETFramework,Version=v4.6.2" in the "TargetFrameworks"

I can't run my unit tests.
I have the next error:
Your project does not reference ".NETFramework,Version=v4.6.2"
framework. Add a reference to ".NETFramework,Version=v4.6.2" in the
"TargetFrameworks" property of your project file and then re-run NuGet
restore.
In app.config:
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2"/>
</startup>
In Project > Properties > Application > TargetFramework (.NET Framework 4.6.2)
How can I fix it?
Please make the next steps
Clean solution
Clean folder "packages"
Delete folder "bin"
Delete folder "obj"
I experienced similar issue, but with v4.7.2. Namely, I kept getting build log message like this:
error : Your project does not reference ".NETFramework,Version=v4.7.2" framework. Add a reference to ".NETFramework,Version=v4.7.2" in the "TargetFrameworks" property of your project file and then re-run NuGet restore.
Despite the fact that it looked similar, none of the above proposed steps worked for me. I kept seeing this message after each build. Nothing seemed to be able to help.
In fact, the problem was related to that, due to migration, I had to put two projects in one folder of code. One of them was targeted at .Net Core, another at .Net Framework, both referenced same .Net Standard libraries. Apparently, they share the same obj folder where Core projects put project.assets.json file. Actually, exactly this file interferres with the Framework project preventing its normal build. Seems even if you performed Migrate from packages.config to PackageReference... which was recommended as one of possible solution.
You can try to fix the issue by putting the following snippet into your Framework project file:
<Project>
...
<PropertyGroup>
<BaseOutputPath>$(MSBuildProjectDirectory)/out/$(MSBuildProjectName)/bin</BaseOutputPath>
<BaseIntermediateOutputPath>$(MSBuildProjectDirectory)/out/$(MSBuildProjectName)/obj</BaseIntermediateOutputPath>
</PropertyGroup>
...
</Project>
It immediately worked for me, it was only later when I attentively read why we need it and why it works. I unexpectedly found it in part 2 of Migrating a Sample WPF App to .NET Core 3 under Making sure the .NET Framework project still builds section. BaseOutputPath and BaseIntermediateOutputPath msbuild variables can be found there, not sure if they are documented well anywhere.
That happened to me when opening a VS2015 project in VS2017. Deleting the project.assets.json from the obj folder did the trick.
Anyway, the Framework from the message was missing in the file, I did not add it there though, went with deleting it.
git clean -xdf
That should do the trick. It worked for us also in Jenkins. (we simply replayed the failed build with a modified script that ran git clean first).
For some reason MSBuild / Visual Studio get confused when switching between branches that target different versions of .NET Framework, so I had to do git cleans regularly while switching between branches.
The file that was causing issue for me was obj/project.assets.json inside project folder. Deleting it and rebuilding the project worked.
I had deleted the obj folder and rerun the build after choosing the target framework required in the property window it worked for me.
I up-voted Larissa but I thought it might be helpful to know how I got into this. I added a .net standard project file to my build (we target lots of platforms) and it produced the debris found in the obj folder. When the android sanity build came around, it threw up on the obj folder. My solution was to clean that folder out as a pre-build step. This is a difficult problem because it was working just fine for years...needle meet haystack.
For my case, delete the .pkgrefgen/ folder under the project folder works, it contains a file project.assets.json that refer to old .net framework
I ran into the same thing with .net 4.71. In my case, I simply migrated from packages.config to "package references" per
Migrate from packages.config to PackageReference
... and it fixed my issue. For me, I was going to do this anyway, so if you're going this way already, I'd just skip the above and migrate to package references.
Renaming the project solved the error for me. The issue happened after I created .NET Core project, then I deleted it and created a .NET Standard one with the same name. Obj folder was not present at all. Deleting bin folder, packages, clean and rebuild solution and getting latest with override did not help.
I have not tried this, but this thread proposed workaround is to include into csproj tag:
<ResolveNuGetPackages>false</ResolveNuGetPackages>
I am using a very old .NET project, and it was working fine until it stopped all of a sudden. Upgrading Visual Studio fixed for me thou.
On VS2019 I had to follow the error message and edit the project.json file that was in the project directory.
was ".NETFramework,Version=v4.0": {} // whatever the copied project was set to
now ".NETFramework,Version=v4.7.2": {} // set to whatever the current build is set to
Problem: In VS2017. Missing reference to .netframework 4.5.2, even though it was referenced as the target framework.
My solution: Verified framework was installed and restarted machine. After a git clean and simply right clicking on the solution in the explore and 'Restore nuget packages' did the trick.
For whatever reason, I got this build error in VS2022.
The same build in VS2019 was successful.
I had the same issue in CI/CD process, when i had upgraded .net framework version from 4.6.1 to 4.7.2 which worked fine locally without any other modification.
However, the jenkins 'slave' node where the build was actually getting generated had some issue with nuget restore and it was not able to pick the latest build for some reason.
Logged into jenkins slave machine/node (basically the machine which jenkins uses to create the build/artifact), go to deployment path and then try deleting projects old builds along with .nugets folder and trigger CI/CD process again worked for me.
This error also occurs if you have removed an old SDK that provided nuget packages, but it is still referenced in your package sources list under Nuget manager/settings. Remove the nuget package source no longer in use to fix this. Otherwise, Visual studio on building will create the project.assets.json file with a reference to the old sdk and if the path is not there, you get the OP's error.
In my case, I had DevExpress 20.2 in my list which I removed to resolve this issue.

"Build failed" on Database First Scaffold-DbContext

I'm trying to generate classes from a database (EntityFramework's database first approach).
For convenience, I'm more or less walking along with this tutorial:
https://docs.efproject.net/en/latest/platforms/full-dotnet/existing-db.html
I'm at a point where I am running the equivalent of this line of code in the Visual Studio Package Manager Console:
Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -Verbose
This line of code is generating the error (with -Verbose mode on):
Using startup project 'EFSandbox'.
Using project 'EntityFrameworkCore'
Build started...
Build failed.
I see no other options that produce any meaningful output, and I see no documentation on this particular error. If it helps at all, this project does not have a project.json file, currently. Everything is in the .csproj file, which I have not manually edited.
Two most important tips:
[1] - Make sure that your project builds completely before you run a new scaffold command.
Otherwise...
You'll start writing a line of code.
You'll realize a required DB column is missing from your model.
You'll go to try to scaffold it.
Twenty minutes later you'll realize the reason your build (and scaffold command) is failing is because you literally have a half written line of code. Oops!
[2] - Check into source control or make a copy:
Allows you to easily verify what changed.
Allows rollback if needed.
You can get some very annoying 'chicken and egg' problems if you get unlucky or make a mistake.
Other problems:
If you have multiple DLLs make sure you aren't generating into the wrong project. A 'Build failed' message can occur for many reasons, but the dumbest would be if you don't have EFCore installed in the project you're scaffolding into.
In the package manager console there is a Default project dropdown and that's probably where your new files ended up if you're missing an expected change.
A better solution than remembering to set a dropdown is to add the -Project switch to your scaffolding command.
This is the full command I use:
For EF Core 2
Scaffold-DbContext -Connection
"Server=(local);Database=DefenderRRCart;Integrated
Security=True;Trusted_Connection=True;" -Provider
Microsoft.EntityFrameworkCore.SqlServer -OutputDir RRStoreContext.Models
-context RRStoreContext -Project RR.DataAccess -force
For EF Core 3
dotnet ef dbcontext scaffold
"Server=tcp:XXXXX.database.windows.net,1433;Initial
Catalog=DATABASE_NAME;Persist Security Info=False;User
ID=USERNAME;Password=PASSWORD;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection
Timeout=30;" Microsoft.EntityFrameworkCore.SqlServer -o DB.Models
--context-dir DB.Contexts --context RRDBContext --project RR.EF.csproj --force --use-database-names
Note: -force will overwrite files but not remove ones that don't exist any more. If you delete tables from your DB you must delete the old entity files yourself (just sort in Explorer by date and delete the old ones).
Full Scaffolding reference:
EF Core 2:
https://docs.efproject.net/en/latest/miscellaneous/cli/powershell.html#scaffold-dbcontext (this
EF Core 3:
https://learn.microsoft.com/en-us/ef/core/miscellaneous/cli/dotnet
Manually building the project by pressing Ctrl+Shift+B helped me to see the errors that were causing the build to fail.
I know this is old, but I spent a while trying to figure this out today, so I hope this helps someone.
I have a .Net Core project but I want to scaffold my files into a .Net Standard class library. DbContext-Scaffold in the package manager console didn't work for me, but dotnet ef dbcontext scaffold in a regular command prompt did.
I had to install these packages in my class library:
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.Tools
I had to have a .Net Core project set as the startup project in my solution and that project had to have a reference to my class library. I think that last part is what I was missing that kept me scratching my head for so long.
Finally, I cd'd into the class library from a command prompt and ran this:
dotnet ef dbcontext scaffold "<connection string>" Microsoft.EntityFrameworkCore.SqlServer -o <output folder> -s <relative path to my startup project>
I still had this problem even when I ensured that my project (which had EF Core installed) built correctly. It still failed with the "Build failed." message, which is visible when using the -Verbsose flag.
I had to do this in my case:
Create a throw-away ASP.NET Core web application solution
Add the EF Core NuGet package to the solution
Add the EF Core Sql Server provider NuGet package (because I'm using SqlServer)
Add the EF Core Tools NuGet package
Switch -Project in the package manager console command to point to my newly-created (and EF Core-provisioned) project. The last step was just for good measure, since there was only one project in my throw-away solution.
It seems that this whole process requires an ASP.NET core project (or just a .NET Core project that isn't a class library) somewhere in the solution, presumably set as the solution startup project too.
Make sure your project isn't running, for some reason this command doesn't work while my API is running in the background.
Thanks to the above, rebuilding the project solution solved this. Some crucial caveats for me personally were:
Running the dotnet build was not enough (I had asssumed it was)!
In visual studio menu, Build > Build solution (Ctrl + Shift + B)
I believe I was simply trying to run the dotnet build command while inside a child project (myProject.data)
Rebuilding the parent project (myProject) solution was the key
I hope that helps someone else who was equally confused!
Using VS2017 Preview 3, .NET Core 2 (PREVIEW) I had all sorts of issues, but eventually I took the approach suggested above and created a brand new solution.
Created new .NET Core solution
Edited project file and changed 1.0 to 2.0:
<TargetFramework>netcoreapp2.0</TargetFramework>
Closed/re-opened solution
Then, added the Entity Framework:
In PackageManager console:
Install-package Microsoft.EntityFrameworkCore.SqlServer -Version 2.0.0-preview2-final
Install-package Microsoft.EntityFrameworkCore.Tools -Version 2.0.0-preview2-final
Install-package Microsoft.EntityFrameworkCore.Design -Version 2.0.0-preview2-final
Edited project file, and added:
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.Dotnet" Version="2.0.0-preview2-final" />
Then;
Opened the Powershell command prompt and changed directory into Scaffold
project folder
Ran: dotnet ef dbcontext scaffold
"Server=DESKTOP-MB70B7U; Database=ForexForme;
Trusted_Connection=True" Microsoft.EntityFrameworkCore.SqlServer -o
Models
Where you put in your own connection string!
Models is the name of my directory where I put all my classes
Build complete solution and see where it fails. I had some NuGet projects hidden away in a folder that didn't build. Only while rebuilding the solution I found out what the problem was. Everything needs to build or else Scaffold will fail.
If entity-framework returns build failed, most probably you have some kind of error in any of your projects.
Even if the project you are running the command on, is clean and error-free, other projects in that solution can cause the build failed response.
Solution
Rebuild the whole solution. Most probably you'll find that error in solution-rebuild process.
Make sure the project you want to run command on, is selected in Default project drop-down inside Package Manager Console
Re-run the command.
If you use multiple projects in the solution, check the default project in the package manager.
I resolved it with right click on projects and "Unload Project" let only the EF project and run the commands
For me the issue was that I was trying to set it up in a new blank console project inside of the solution, which had no files, so the scaffolding tried to use this project as a startup project and couldn't find Main. I fixed it by adding a new file with an empty main
I has same Build Fails Error...
I after close visual studio and open again it, run Clean Solution and then Rebuild Solution from Build Menus after this Scaffold-Dbcontext build successfully
For me, my project built in Visual Studio but I had to specify a version for "Microsoft.AspNetCore.App" when running Scaffold-DbContext.
So instead of:
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
<RuntimeFrameworkVersion>2.1.6</RuntimeFrameworkVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App"/>
</ItemGroup>
I had to have:
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" Version="2.1.6" />
</ItemGroup>
Make sure your build works fine.
Run the scaffold command from the package console, your command should work:
Scaffold-DbContext 'Data Source=TEST-XY010;Initial Catalog=TESTDB;Trusted_Connection=True' Microsoft.EntityFrameworkCore.SqlServer -Context HOPWAContext -OutputDir TESTModel -Force
I resolved it by stopping my server and then running it again.
This stopped working for me today. So I tried running the dotnet scaffold command from the command line and it worked first time. Don't ask me!!
I had a issue that I have some non-scaffolded code in my DbContext project (partial classes for interfaces) that relied on generated files. As part of the re-scaffold though, I delete all previously generated code and of course this causes the project to fail building and thus scaffolding.
My work around is to have a custom "Scaffold" configuration on the project that simply removes from compilation a whole subfolder where any code-gen dependent files are to live.
If this is a path for you, edit your DbContext's .csproj and add:
<ItemGroup Condition="'$(Configuration)' == 'Scaffold'">
<Compile Remove="NonGenerated\**\*.*" />
</ItemGroup>
and change your command line to include a --configuration Scaffold parameter. A powershell sample of how I do this is as such:
# Run from DbContext project root
$DbContextProjName = "Engine.Common.Dal"
#conStr = "...." #Your ConnectionString here, or loaded otherwise
if (Test-Path "Generated"){
Remove-Item -Recurse -Force "Generated"
}
#Entities/Context in own folder for easy delete then regen, entity-dependant files go in NonGenerated
dotnet ef dbcontext scaffold `
$conStr `
"Microsoft.EntityFrameworkCore.SqlServer" `
--context DatabaseContext `
--data-annotations --force --no-onconfiguring `
--namespace "$($DbContextProjName)" `
--output-dir "Generated" `
--project "$($DbContextProjName).csproj" `
--startup-project "$($DbContextProjName).csproj" `
--configuration "Scaffold"
if (! $?){
throw "dotnet ef scaffold failed!"
}
Make sure you have all packages and press ctrl + shift +b to build the solution. It works to me.
Make sure your project is not running
Make sure your project is compiling
That worked for me.
1-
Make sure the build is successful, to check to build is successful go-to solution explorer and right-click on solution name and rebuilt solution, all project will build successful and good to go.
2-
Install NuGet package Microsoft.EntityFrameworkCore.SqlServer
Install NuGet package Microsoft.EntityFrameworkCore.Tools
Install NuGet package Microsoft.EntityFrameworkCore.Design
check all the versions should be the same for NuGet packages like (3.1.3) and install inside class library if you are following onion architecture.
3-
Try now if still, it failed check db context and reference to class library should be added inside asp.net core web project.

Categories