/ notes / sql

Entity Framework notes

Database-first / reverse engineering / scaffolding

This is the approach to use when you have an existing database, the database is designed outside the application, the database is used by many application, etc. Personal opinion: always use this approach.

Instead of the following steps at the command-line, consider to use EFCorePowerTools extension for Visual Studio 2022.

General setup:

Install/Update Entity Framework Core - CLI Tools

dotnet tool install --global dotnet-ef
dotnet tool update --global dotnet-ef
dotnet tool list --global
dotnet ef

In the target project:

Let’s code

string dbConnString = "Data Source=(localdb)\\MSSQLLocalDB; Initial Catalog=ContosoSales1M;";

using (var dbCtx = new ContosoSales1MContext(
                        new DbContextOptionsBuilder<ContosoSales1MContext>()
                              .UseSqlServer(dbConnString)
                              /*.LogTo(Console.WriteLine)*/
                              .Options))
{
    var firstCustomer = dbCtx.Customer.First();
    Console.WriteLine($"First customer: {firstCustomer.CustomerKey} {firstCustomer.GivenName}");
    // ......
}