Generating Entity Framework classes for Database First project

Not all projects, or development teams, use Code First with Entity Framework for building and maintaining their database.  There are plenty of reasons for doing it either way but that discussion is outside of the scope of this post.  What this post is going to focus on is generating your EF classes in a Database First environment.

Microsoft has plenty of great documentation for developers and one such post that I used recently was Getting Started with EF Core on ASP.NET Core with an Existing Database.  My setup is Visual Studio 2017 Community Edition and a .NET Core 2.1 project structure.  The database is running on a free, local instance of SQL Server 2017 and consists of a handful of tables.  To generate the classes I utilized the Package Manager Console (PMC) in Visual Studio and the Scaffold-DbContext command.

Scaffold-DbContext "Data Source=localhost\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True;" Microsoft.EntityFrameworkCore.SqlServer -outputDir Repository -Verbose

The connection string is pretty basic.  I’m telling it to connect to a database on my machine called MyDatabase and use my Windows Credentials for authentication.  The files generated should go into the directory called Repository in my project.  And for help with debugging any problems I include the -Verbose parameter.

Upon completion all generated files were open in my VS instance for inspection and located in the folder I set as the output destination.  If this didn’t happend and you have an error message make sure that your project builds on its own.  If the project doesn’t build then the Scaffold-DbContext won’t be able to generate the files.  One thing to check before you submit your code to any repository is that in your Context.cs class the connection string used for Scaffold-DbContext is hard-coded into the file.  If the code is going to a public repository you’ll want to make sure this line is removed.