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:
- add nuget package
Microsoft.EntityFrameworkCore.SqlServer
- add nuget package
Microsoft.EntityFrameworkCore.Design
- at the command-line, from the project folder:
dotnet ef dbcontext scaffold "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=TestDB" Microsoft.EntityFrameworkCore.SqlServer --output-dir EF --no-onconfiguring --force
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}");
// ......
}
Links:
- Official documentation: https://learn.microsoft.com/en-us/ef/core/managing-schemas/scaffolding/?tabs=dotnet-core-cli
- Issue - Reverse Engineer: Better support for namespaces https://github.com/dotnet/efcore/issues/3988