If you want to use Entity Framework to access pre-existing SQL tables (the database first approach) then providing they’re all keyed up correctly it’s possible to generate all the required classes and the DB context for them with just a few commands.

First you need to install the following 3 NuGet packages.

  • Microsoft.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.Tools
  • Microsoft.EntityFrameworkCore.SqlServer

You then need to run the Scaffold-DbContext command in the Package Manger Console window. This has the following format.

Scaffold-DbContext [-Connection] [-Provider] [-OutputDir] [-Context] [-Schemas>] [-Tables>] 
                   [-DataAnnotations] [-Force] [-Project] [-StartupProject] [<CommonParameters>]

In my case I just required the Connection, Provider and OutputDir arguments.

Scaffold-DbContext "Server=tcp:SERVER.database.windows.net,1433;Initial Catalog=DATABASE;Persist Security Info=False;User ID=USERNAME;Password=PASSWORD;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

0 Comments

Leave a Reply

Avatar placeholder

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