'MsBuild cannot resolve MsBuildMajorVersion

I have Visual Studio Solution with more than 100 projects. Five of them have Fody's nuget packages installed (version 6.0.3). When I try to build the Solution I get the following error:

Fody.6.3.0\build\Fody.targets(38,12): error MSB4086: A numeric comparison was attempted on "$(MsBuildMajorVersion)" that evaluates to "" instead of a number, in condition "($(MsBuildMajorVersion) < 16)"

After this failed build I try to build repeatedly and after several attempts (sometimes one, sometimes five) building finishes with success. I was trying to reinstall all nuget packages, clear nuget caches, reinstall Visual Studio, set MSBUILDDISABLENODEREUSE variable and nothing helped.

Visual Studio 2019 is in version 16.8.4 and all projects have .NET Framework in version 4.8.

UPDATE:

The problem exists on my machine only. On colleagues' workstations, everything works fine. I found the tip that after an unsuccessful build Visual Studio should be restarted and the build process is successful. This tip is a sufficient workaround for me.



Solution 1:[1]

Try to install the latest Costura.Fody nuget package additionally on those five projects and also try to update Fody nuget package to the latest 6.3.0 version.

And then rebuild your project to check whether the issue happens.

Solution 2:[2]

I was able to fix this problem by adding to .csproj code to restore nugets (just copied from project created in VS 2017). Converting packages.config to PackageReference also worked for me but causes some other problems when build by msbuild.

Need to add following lines at the end of first PropertyGroup

  <SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\..\</SolutionDir>
  <RestorePackages>true</RestorePackages>
</PropertyGroup>

And following line EnsureNuGetPackageBuildImports target:

  <Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
  <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">

See attached screenshot for more details:

enter image description here

Solution 3:[3]

I was able to fix this problem by cleaning up my whole resolution and trying to run a rebuild, then succeeded to rebuild the project.

Maybe you should try.

Solution 4:[4]

May sound silly, but for me all I needed to do, is simply upgrading Fody nuget to another version and switching back to the original version, and my code compiled successfully again. Might not be your case, but worth to try this 2 minutes solution.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mr Qian
Solution 2 Vasiliy Vdovichenko
Solution 3 0xAA55
Solution 4 Tiger Galo