122

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.

LightToTheEnd
  • 1,399
  • 2
  • 9
  • 11
  • 9
    Do you get any errors/warnings when you recompile the whole solution? – Ignas Aug 15 '16 at 18:57
  • @Ignas Did that, and yes, I got dependency errors that didn't exist before I recompiled, and that just shouldn't have existed. Rather than try to fight it, I remade the solution. I have a new problem now, though. Guess that I should make a new question after a bit (if this one is similar) as opposed to editing this one. – LightToTheEnd Aug 15 '16 at 19:24
  • Think your issue is that you have to have a project.json in order to declare the EFC tools. Try rewriting in the correct project type and this could generate a json. – Webezine Aug 17 '16 at 14:06
  • 3
    For me, what got it working was to make sure the entire solution ( not just the project) builds successfully before issuing the scaffold command. – manish gupta Apr 02 '18 at 17:04
  • I wanted to briefly update this question since it got a lot of attention - this was on a much older build of EF Core than what is currently available, and after several other problems, the solution that we ended up going with was EF6 until Core had more time to settle. Even EF6 posed problems, but we got it set up much more reliably. – LightToTheEnd Feb 15 '19 at 16:49
  • Unload the dependency projects which has errors – Anji V May 10 '19 at 06:35
  • 1
    there's a (not documented) --NO-BUILD option – ValGe Aug 27 '20 at 11:08
  • 1
    dotnet ef dbcontext scaffold "(connectionstring)" Microsoft.EntityFrameworkCore.SqlServer --no-build – ValGe Aug 27 '20 at 11:09
  • I had to make sure all projects in the solution built successfully even client projects not directly involved on EF before getting rid of this issue – Matias Masso May 06 '22 at 14:45

23 Answers23

232

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

Simon_Weaver
  • 140,023
  • 84
  • 646
  • 689
  • also make sure Project.JSON files don't have comments in them – Simon_Weaver Dec 08 '16 at 22:05
  • And yes you can scaffold into a 'class library' project if you prefer your dataaccess logic in a separate file, but the primary project needs to be an aspnet core project – Simon_Weaver Dec 26 '16 at 21:36
  • Tip: Make sure to run from the package manager console. Doesn't work for me running from Visual Studio command prompt – Simon_Weaver Jun 19 '17 at 20:33
  • Your answer led me into right direction. In my case I had some dependencies which were not being built. – Manoz Aug 04 '17 at 12:15
  • In my case I had two start up projects(Api & IdentityServer4) when I ran the command it didn't update the models and not even throwed any error. Then I came up setting Api as the startup proj and ran the command it worked like a charm. Setting up a single proj. as the start up seems to be the main reason. – Zaker Dec 09 '17 at 05:45
  • 2
    what do you do if for instance you removed an entity file ? Scaffold won't work because you are missing this file but it won't scaffold because it doesn't build. Quite annoying. – sofsntp Mar 26 '18 at 09:34
  • sofsntp, this is exactly the question I have. In my case, a team member did the scaffolding without specifying the output folder, or only naming the application root (the one with csproj). That's not where model POCOs should go! But now, I can't build, and I can't re-scaffold using the proper output directory. – EoRaptor013 Mar 30 '18 at 22:52
  • @sofsntp that's exactly why I wanted the entities in a separate project altogether :-) then it's easier to comment things out. Also make sure to look in explorer sorted by date to remove files that are obsolete – Simon_Weaver Aug 28 '18 at 08:09
  • I had some quite weird file locking issue recently, that required a reboot. I was getting some very odd errors trying to scaffold - as if some common Microsoft DLL was not available with no further useful information whatsoever. One of those rare cases where a reboot was resisted, but turned out to be the solution. Unrelated directly to the above - but adding it here since it's yet another way to end up with scaffold build issues. – Simon_Weaver Feb 08 '19 at 10:41
  • 16
    Annoyingly you seem to need to be able to build the entire solution. I had errors in other projects but the project to scaffold was fine. Solution was to select the other projects and "unload" them. Then scaffold, then reload. – Sam Mar 28 '19 at 03:18
  • How to get final status of scaffold-dbcontext command?Where can I get log details or error details? – Karthic G May 10 '21 at 15:16
  • @KarthicG I've never come across needing to do this. Other than comparing the files from last known commit to source control. Any errors should appear, and if there's no errors then it succeeded. – Simon_Weaver May 10 '21 at 17:55
  • automation process of doing this scaffold command in c# , by any case if build failed , how can I identify what cause it is? – Karthic G May 11 '21 at 08:52
  • 2
    --> Make sure that your project builds completely <-- Good! – Seraphim's Jun 22 '21 at 08:53
  • No sense, what doesn't build is the model – Leandro Bardelli May 04 '22 at 18:44
  • 1
    What do you know? The error was in another project. It's weird that the build failed error did not specify where the error occur until the entire solution is built. – Jean-Joseph Feb 12 '23 at 13:14
  • @Sam damn how annoying. that was it! the entire solution needs to build. thanks! – symbiont Feb 22 '23 at 21:19
24

Manually building the project by pressing Ctrl+Shift+B helped me to see the errors that were causing the build to fail.

Mxaza
  • 474
  • 5
  • 12
  • As the accepted answer already said years before. "Make sure that your project builds completely before you run a new scaffold command." – Gert Arnold Nov 11 '20 at 11:20
  • 1
    This did not reveal the issue for me. Visual Studio kept building successfully, even after cleans. Adding the --verbose flag to `dotnet ef scaffold` did not help. I had to do a `dotnet build` to see the error. – Becca Dee Jan 13 '21 at 13:31
  • 1
    Thanks a lot! Entering Ctrl + Shift + B displayed all my build errors in VS & saved my time. – Sanushi Salgado Sep 15 '21 at 05:27
15

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>
melicent
  • 1,221
  • 15
  • 22
6

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.

bcr
  • 1,983
  • 27
  • 30
  • 2
    This is probably one of the more useful entries on this page. The -verbose flag should push in the correct direction as it covers the multitude of things which can go wrong with scaffold. – Regianni Jun 15 '20 at 10:53
6

Thanks to the above, rebuilding the project solution solved this. Some crucial caveats for me personally were:

  1. Running the dotnet build was not enough (I had asssumed it was)!
  2. 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!

Joel Balmer
  • 1,428
  • 2
  • 19
  • 21
5

Make sure your project isn't running, for some reason this command doesn't work while my API is running in the background.

Josh Siegl
  • 735
  • 1
  • 9
  • 16
4

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.

  1. Created new .NET Core solution
  2. Edited project file and changed 1.0 to 2.0: <TargetFramework>netcoreapp2.0</TargetFramework>
  3. Closed/re-opened solution

Then, added the Entity Framework:

  1. 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
  2. Edited project file, and added: <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.Dotnet" Version="2.0.0-preview2-final" />

Then;

  1. Opened the Powershell command prompt and changed directory into Scaffold project folder
  2. 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
James Joyce
  • 1,694
  • 18
  • 20
4

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.

Guido Neele
  • 778
  • 1
  • 7
  • 20
  • This did not reveal the issue for me. Visual Studio kept building successfully, even after cleans. Adding the --verbose flag to `dotnet ef scaffold` did not help. I had to do a `dotnet build` to see the error. – Becca Dee Jan 13 '21 at 13:31
4

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.
Inam Ul Huq
  • 732
  • 7
  • 8
4

If you use multiple projects in the solution, check the default project in the package manager.

4

I resolved it with right click on projects and "Unload Project" let only the EF project and run the commands

3

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

Austin_Anderson
  • 900
  • 6
  • 16
3

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

ashkufaraz
  • 5,179
  • 6
  • 51
  • 82
1

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>
Cpt.Ohlund
  • 2,589
  • 1
  • 20
  • 15
1

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
סטנלי גרונן
  • 2,917
  • 23
  • 46
  • 68
Shakil
  • 51
  • 3
1

I resolved it by stopping my server and then running it again.

tblev
  • 422
  • 4
  • 13
0

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

Regianni
  • 229
  • 1
  • 3
  • 11
  • It broke again before I discovered the --verbose flag, which delivered the stacktrace which allowed me to identify the problem. Would probably help if the error was output irrespectively of this flag. – Regianni Jun 16 '20 at 08:51
0

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!"
}
admalledd
  • 428
  • 3
  • 11
0

I had the same problem, but to me, it happened when I made EF -Migrations. This error can cause both when you add a command for Migration (what was my case) or Scaffolding the DB. When you start the command, first, it builds the project and if there is a problem during the build process, it stops, does not continue, and returns just "Build failed" message. There is no Log Error message or additional information about the problem. The previous answers are correct. Firstly and mainly you have to check if there is no compile error and the project is building successfully.

  • Right-click on the project level: Clean.
  • Right-click on the project level: Build.

Or if you have multiple projects in one solution is better to do this at the Solution Level to check the entire application.

Let me say about my case where I have the same problem.

I have a large application with multiple projects in 1 solution which are not related

Without: Add > Project Reference...

to each other i.e. Microservices and what made it difficult for me to do a Migration and get -

Builder Failed

in one of the services i.e. "Order API". The problem was in another service, i.e. "Basket API" I made some changes earlier here, injecting an extra dependency in the constructor in that API Controller, and without noticing that it was missing mocking this dependency for this Controller where I did a unit test which causes Compile Error. As "Order API" was a startup project and my focus was here, didn't show me the compile error through the Re-Building only the Order API, but there was a problem when I was adding the migration in the Order API and the cause of the problem was in the Basket API > Integration Test.

  • This is the example of my project solution:

example of the project structure looks like

I hope I explained well what happened in my case with "EF Migration - Builder Failed"; maybe it will be useful information.

  • Also you can try to turn off visual studio, restart your PC and try again.
  • I found some link about **EF - Scaffold ** Builder Failed:

Scaffold-Dbcontext build failed using EFCore commands

Viktor38
  • 13
  • 1
  • 6
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 09 '23 at 12:13
0

In my case, I run Scaffold-DbContext ... to generate the models. Then, I delete the generated models, run the command and it says Build failed.

What I have to do is to delete the generated context file generated by Scaffold-DbContext also and run the command again and it works for me.

Tuan Hoang
  • 586
  • 1
  • 7
  • 14
-1

Make sure you have all packages and press ctrl + shift +b to build the solution. It works to me.

  • As the accepted answer already said years before. "Make sure that your project builds completely before you run a new scaffold command." – Gert Arnold Nov 11 '20 at 11:21
-1
  1. Make sure your project is not running
  2. Make sure your project is compiling

That worked for me.

-1

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.