EntityFramework Core Scaffolding


If you already have a database and want to use EF Core for your database/object mapping, the Scaffold-DbContext command can be run from within Visual Studio, using the Package Manager Console. If it isn’t open, you can get to it from the View/Other Windows menu command. This is an example of how to generate DbContext and entity mapping objects:

Scaffold-DbContext “Server=.\SQLEXPRESS01;Database=***;Trusted_Connection=True” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Objects

The command targets SQL Server using the currently logged on user account. Make sure you select the correct project, if you more than one in your solution, from the Default Project list in the
Package Manager Console.

Notice how I have a single backslash for the server name. In your connection string, potentially stored in the appsettings.json file, you’ll need two backslashes, Server=.\\SQLEXPRESS01. If you have two backslashes when running the Scaffold-DbContext command, the command will fail, with this exception:

System.InvalidOperationException: Instance failure.
at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover)

Don’t forget the -Force option in your command, if you want to replace an existing DbContext and mapping objects.

Advertisements