Blazor with Database First

In our company we are using EF Core Power Tools for generating the context and the model classes for Entity Framework Core.

You can find the corresponding documentation under https://github.com/ErikEJ/EFCorePowerTools/wiki/Reverse-Engineering. With this tool you can directly generate the classes within Visual Studio and you also can store the configuration that you easily can update your classes if the database changes.


Rene's answer is correct it just needs 2 amendments:

You need to add a / before the > on the last package reference.

You will also need to reference "Microsoft.EntityFrameworkCore.Design" Version="3.1.1"


Add the following Packages to your project:

<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="3.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.1">

Add your database connection string to appsettings.json

{
  "ConnectionStrings": {
    "MyConnection": "Server=tcp:<yourServer>,1433;Initial Catalog=<yourDatabase>;Persist Security Info=False;User ID=<yourDatabaseUserName>;Password=<yourDatabaseUserPassword>;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=True;Connection Timeout=30;"
  }
}

Open PackageManagerConsole and type

Scaffold-DbContext -Connection name=MyConnection -Provider Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context MyDbContext -Force

This will create a Models folder in your project containing MyDbContext.cs plus a <TableName>.cs-file for each table in your database.

Note: For the first import of your database you don't need the -Force option in the Scaffolding. It will be needed though, if you make changes in your database after the first import and want to update your cs-classes afterwards.