“Build failed” on Database First Scaffold-DbContext

后端 未结 18 1667
醉梦人生
醉梦人生 2020-12-24 04:31

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: ht

18条回答
  •  攒了一身酷
    2020-12-24 05:02

    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://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/dotnet

提交回复
热议问题