title
stringlengths
3
46
content
stringlengths
0
1.6k
13:357
13:358
Let’s go to the Package Manager Console and ensure that WWTravelClubDB is selected as our default project.
13:359
Now, type Add-Migration initial and press Enter to issue this command. Verify that you added the Microsoft.EntityFrameworkCore.Tools NuGet package before issuing this command; otherwise, you might get an “unrecognized command” error:
13:360
13:361
Figure 13.1: Adding the first migration
13:362
initial is the name we gave our first migration. So, in general, the command is Add-Migration <migration name>. When we operate on an existing database, we must add the -IgnoreChanges option to the first migration (and just to that) so that an empty migration is created. References to the whole set of commands can be found in the Further reading section.
13:363
13:364
13:365
If, after having created the migration but before having applied the migration to the database, we realize we made some errors, we can undo our action with the Remove-Migration command. If the migration has already been applied to the database, the simplest way to correct our error is to make all the necessary changes to the code and then apply another migration.
13:366
As soon as the Add-Migration command is executed, a new folder appears in our project:
13:367
13:368
13:369
Figure 13.2: Files created by the Add-Migration command
13:370
20210924143018_initial.cs is our migration expressed in an easy-to-understand language.
13:371
You may review the code to verify that everything is okay. You may also modify the migration content (only if you are enough of an expert to do it reliably) or simply undo the migration with the in Remove-Migration Remove-Migration command, which is the advised way to proceed when we discover errors.
13:372
Each migration contains an Up method and a Down method.
13:373
The Up method implies the migration, while the Down method undoes its changes. Accordingly, the Down method contains the reverse actions of all the actions included in the Up method in reverse order.
13:374
20210924143018_initial.Designer.cs is the Visual Studio designer code, which you must not modify, while MainDbContextModelSnapshot.cs is the overall database structure snapshot. If you add further migrations, new migration files and their designer counterparts will appear, and the unique MainDbContextModelSnapshot.cs database structure snapshot will be updated to reflect the database’s overall structure.
13:375
The same command can be issued in an operating system console by typing dotnet ef migrations add initial. This command must be issued from within the project’s root folder (not from within the solution’s root folder).
13:376
However, if Microsoft.EntityFrameworkCore.Design is installed globally with dotnet tool install --global dotnet-ef, then we can use it in a project after adding it to that project by typing dotnet add package –-project <project path> Microsoft.EntityFrameworkCore.Design. In this case, commands can be issued from any folder by specifying the --project <project path> option.
13:377
Migrations can be applied to the database by typing Update-Database in the Package Manager Console. The equivalent console command is dotnet ef database update. Let’s try using this command to create the physical database!
13:378
The next subsection explains how to create database stuff that Entity Framework is unable to create automatically. After that, in the next section, we will use Entity Framework’s configuration and the database we generated with dotnet ef database update to create, query, and update data.
13:379
Understanding stored procedures and direct SQL commands
13:380
Some database structures, like, for instance, stored procedures, can’t be generated automatically by the Entity Framework Core commands and declarations we described previously. Stored procedures such as generic SQL strings can be included manually in the Up and Down methods through the migrationBuilder.Sql(`<sql command>`) method.
13:381
The safest way to do this is by adding a migration without performing any configuration changes so that the migration is empty when it’s created. Then, we can add the necessary SQL commands to the empty Up method of this migration and their converse commands in the empty Down method. It is good practice to put all the SQL strings in the properties of resource files (.resx files).
13:382
Stored procedures should replace Entity Framework commands in the following circumstances:
13:383
13:384
When we need to perform manual SQL optimizations to increase the performance of some operations.
13:385
When Entity Framework doesn’t support the SQL operation, we need to perform. A typical example is the increment or decrement of a numeric field that occurs in all booking operations (air travel, hotels, and so on). Actually, we might replace the increment/decrement operation with a database read, an in-memory increment/decrement, and finally, a database update, all enclosed in the same transaction scope. However, this might be overkill for performance.
13:386
13:387
Before starting to interact with our database, we can perform a further optional step: model optimizations.
13:388
Compiled models
13:389
Starting from version 6, Entity Framework Core introduced the possibility to create precompiled data structures that improve Entity Framework Core’s performance by about 10 times in the case of models with hundreds of entities (see the reference in the Further reading section for more details). This step is accomplished by generating some code that, once compiled together with the data layer project, creates data structures that our context classes can use to improve performance.
13:390
The usage of pre-compilation is advised just after you verify the system experiences slow-downs and also on very simple queries. In other words, it is better to start without pre-compilation and then possibly add it in case of slow-downs caused by the EF infrastructure.
13:391
Code is generated with the Optimize-DbContext command provided by the Microsoft.EntityFrameworkCore.Tool NuGet package that we already installed. The command accepts the folder name to place the code and the namespace to place all classes. In our case, let’s choose the Optimization folder and the WWTravelClubDB.Optimization namespace:
13:392
Optimize-DbContext -Context MainDBContext -OutputDir Optimization -Namespace WWTravelClubDB.Optimization
13:393
13:394
Here, the –Context parameter must be passed the name of our context class. The Optimization folder is automatically created and filled with classes.
13:395
The optimization code depends on the ORM configuration, so the Optimize-DbContext command must be repeated each time a new migration is created.
13:396
Optimizations are enabled by passing the root of our optimization model as an option when an instance of the context class is created. Let’s open the LibraryDesignTimeDbContextFactory.cs file and add the line below:
13:397
builder.UseSqlServer(connectionString);
13:398
//Line to add. Add it after that the optimization model has been created
13:399
builder.UseModel(Optimization.MainDbContextModel.Instance);
13:400
return new MainDbContext(builder.Options);
13:401
13:402
Now, you are ready to interact with the database through Entity Framework Core.
13:403
Querying and updating data with Entity Framework Core
13:404
To test our DB layer, we need to add a console project based on the same .NET Core version as our library to the solution. Let’s get started:
13:405
13:406
Let’s call the new console project WWTravelClubDBTest.
13:407
Now, we need to add our data layer as a dependency of the console project by right-clicking on the Dependencies node of the console project and selecting Add Project Reference.
13:408
Remove the content of the Program.cs file and start by writing the following:
13:409
Console.WriteLine(`program start: populate database, press a key to continue`);
13:410
Console.ReadKey();
13:411
13:412
13:413
Then, add the following namespaces at the top of the file:
13:414
using WWTravelClubDB;
13:415
using WWTravelClubDB.Models;
13:416
using Microsoft.EntityFrameworkCore;
13:417
using WWTravelClubDBTest;
13:418
13:419
13:420
13:421
Now that we have finished preparing our test project, we can experiment with queries and data updates. Let’s start by creating some database objects, that is, some destinations and packages. Follow these steps to do so:
13:422
13:423
First, we must create an instance of our DbContext subclass with an appropriate connection string. We can use the same LibraryDesignTimeDbContextFactory class that’s used by the design tools to get it:
13:424
var context = new LibraryDesignTimeDbContextFactory()
13:425
.CreateDbContext();
13:426
13:427
13:428
New rows can be created by simply adding class instances to the mapped collections of our DbContext subclass. If a Destination instance has packages associated with it, we can simply add them to its Packages property:
13:429
var firstDestination= new Destination
13:430
{
13:431
Name = `Florence`,
13:432
Country = `Italy`,
13:433
Packages = new List<Package>()
13:434
{
13:435
new Package
13:436
{
13:437
Name = `Summer in Florence`,
13:438
StartValidityDate = new DateTime(2019, 6, 1),
13:439
EndValidityDate = new DateTime(2019, 10, 1),
13:440
DurationInDays=7,
13:441
Price=1000
13:442
},
13:443
new Package
13:444
{
13:445
Name = `Winter in Florence`,
13:446
StartValidityDate = new DateTime(2019, 12, 1),
13:447
EndValidityDate = new DateTime(2020, 2, 1),
13:448
DurationInDays=7,
13:449
Price=500
13:450
}
13:451
}
13:452
};
13:453
context.Destinations.Add(firstDestination);
13:454
await context.SaveChangesAsync();
13:455
Console.WriteLine(
13:456
$`DB populated: first destination id is {firstDestination.Id}`);