# test if Entity Framework Core Tools has been installed
dotnet ef
# be sure to run the previous command in the folder of the project where EF has been added# dotnet ef must be installed as a global or local tool
dotnet tool install --global dotnet-ef# installed in ~/.dotnet/tools# Add ~/.dotnet/tools to PATH# update
dotnet tool update dotnet-ef--global# --version 7.0.14
Default Project = the one containing the entity configurations
Startup Project = the one containing the sql server configuration
# test if Entity Framework Core Tools has been installedGet-Help about_EntityFrameworkCore
# installInstall-Package Microsoft.EntityFrameworkCore.Tools
# updateUpdate-Package Microsoft.EntityFrameworkCore.Tools
varconnectionString = builder.Configuration.GetConnectionString("MariaDb"); // get the connection string from the appsettings.json or the secret storevarserverVersion = newMariaDbServerVersion(newVersion(10, 11, 4));
builder.Services.AddDbContext<MyAppContext>(
dbContextOptions => dbContextOptions
.UseMySql(connectionString, serverVersion));
publicclassMyAppContext : DbContext
{
protectedoverridevoidOnConfiguring(DbContextOptionsBuilderoptionsBuilder)
{
optionsBuilder.UseSqlServer("server=localhost;database=test;user=test;password=***"); // hard-coded connection string
optionsBuilder.UseMySql("name=ConnectionStrings:MariaDb", ServerVersion.Parse("10.11.4-mariadb")); // get it from the appsettings.json or the secret storage
optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings["SqlServerConnectionString"].ConnectionString); // WPF
# generate entity classes and context class
dotnet ef dbcontext scaffold
"Server=localhost;Database=MyDb;User=sa;Password=***;"# an harcoded connection string"Name=ConnectionStrings:SqlServer"# get the connection string from the appsettings.json or the secret storage
Microsoft.EntityFrameworkCore.SqlServer # the database provider
--output-dir DataAccess/Entities # output folder for entities
--context-dir DataAccess # output folder for DbContext
--context "MyDbContext"# default context name: DbNameContext
--force # overwrite all the class files
--table table1 --table table2 # scaffold only table1 and table2
AsNoTracking is used to improve performances when you don't need the entities to be tracked for changes. But a better way to improve performances is to use projection so you don't return the whole entity but only the needed fields. This way you don't need AsNoTracking because there is no more entities to track. Include is used to retrieve other entities linked by a foreign key / navigation property. If you use a projection with a navigation property, you don't have to use Include.