How to run Entity Framework Core DB scaffolding from a .bat file in Visual Studio

It’s very handy to wrap the Entity Framework Scaffolding command in a bat file and run it on demand from within Visual Studio. Thankfully this is easy to do…

Installing required dependencies

Open up a command prompt window, navigate to your EF project folder and run the below commands to make sure you have the required dependencies…

dotnet tool install – global dotnet-ef
dotnet add package Microsoft.EntityFrameworkCore.Tools

There’s a good chance you’ll already have these installed.

Create a .bat file which calls the ef dbcontext scaffold command

Put a command similar to below in a .bat file and save it in whatever project your EF DbContext and Models are.

dotnet ef dbcontext scaffold name="AdventureWorks" Microsoft.EntityFrameworkCore.SqlServer – force – output-dir Models – context-dir Context – context EFContext – use-database-names

In the above example we have a named connection which references a connection in the appsettings.json file.

To understand what all the various parameters and flags mean visit the EF Core tools reference (.NET CLI) – EF Core page.

If you’re copying and pasting from above, note WordPress has messed up the dashes. Each flag should have two dashes in front of it.

Executing the .bat file in Visual Studio

At this point you can just double click the file in the project folder and it will scaffold.

To run it from within Visual Studio we can install the Open Command Line extension. After installing the extension we can right click the .bat file and select ‘Execute File’…

Execute File

and we’ll see the CMD window popup…

CMD popup

‘∩╗┐dotnet’ is not recognized as an internal or external command

If you get this strange looking error when trying to run the .bat file it is probably saved in UTF-8 encoding format which cmd.exe doesn’t support. To resolve open the bat file in Notepad and save it with ANSI encoding

Save as ANSI encoding

One thought on “How to run Entity Framework Core DB scaffolding from a .bat file in Visual Studio”

Leave a Reply

Your email address will not be published. Required fields are marked *