title
stringlengths 3
46
| content
stringlengths 0
1.6k
|
---|---|
13:457
|
Console.ReadKey();
|
13:458
| |
13:459
| |
13:460
| |
13:461
|
There is no need to specify primary keys since they are auto-generated and will be filled in by the database. In fact, after the SaveChangesAsync() operation synchronizes our context with the actual DB, the firstDestination.Id property has a non-zero value. The same is true for the primary keys of Package. Key auto-generation is the default behavior for all integer types.
|
13:462
|
When we declare that an entity (in our case, Package) is a child of another entity (in our case, Destination) by inserting it in a parent entity collection (in our case, the Packages collection), there is no need to explicitly set its external key (in our case, DestinationId) since it is inferred automatically by Entity Framework Core. Once created and synchronized with the firstDestination database, we can add further packages in two different ways:
|
13:463
| |
13:464
|
Create a Package class instance, set its DestinationId external key to firstDestination.Id, and add it to context.Packages
|
13:465
|
Create a Package class instance, with no need to set its external key, and then add it to the Packages collection of its parent Destination instance
|
13:466
| |
13:467
|
The latter approach should be preferred when the two entities do not belong to the same aggregate since, in this case, the whole aggregate must be loaded in memory before operating on it to be sure all business rules are correctly applied and to prevent incoherences caused by simultaneous operations on different parts of the same aggregates (see the Aggregates subsection of Chapter 7, Understanding the Different Domains in Software Solutions).
|
13:468
|
Moreover, the latter option is the only possibility when a child entity (Package) is added with its parent entity (Destination) and the parent entity has an auto-generated principal key since, in this case, the external key isn’t available at the time we perform the additions.
|
13:469
|
In most of the other circumstances, the former option is simpler since the second option requires the parent Destination entity to be loaded in memory, along with its Packages collection, that is, together with all the packages associated with the Destination object (by default, connected entities aren’t loaded by queries).
|
13:470
|
Now, let’s say we want to modify the Florence destination and give a 10% increment to all Florence package prices. How do we proceed? Follow these steps to find out how:
|
13:471
| |
13:472
|
First, comment out all previous instructions for populating the database while keeping the DbContext creation instruction:
|
13:473
|
Console.WriteLine(`program start: populate database, press a key to continue`);
|
13:474
|
Console.ReadKey();
|
13:475
|
var context = new LibraryDesignTimeDbContextFactory()
|
13:476
|
.CreateDbContext();
|
13:477
|
//var firstDestination = new Destination
|
13:478
|
//{
|
13:479
|
// Name = `Florence`,
|
13:480
|
// Country = `Italy`,
|
13:481
|
// Packages = new List<Package>()
|
13:482
|
// {
|
13:483
|
// new Package
|
13:484
|
// {
|
13:485
|
// Name = `Summer in Florence`,
|
13:486
|
// StartValidityDate = new DateTime(2019, 6, 1),
|
13:487
|
// EndValidityDate = new DateTime(2019, 10, 1),
|
13:488
|
// DurationInDays=7,
|
13:489
|
// Price=1000
|
13:490
|
// },
|
13:491
|
// new Package
|
13:492
|
// {
|
13:493
|
// Name = `Winter in Florence`,
|
13:494
|
// StartValidityDate = new DateTime(2019, 12, 1),
|
13:495
|
// EndValidityDate = new DateTime(2020, 2, 1),
|
13:496
|
// DurationInDays=7,
|
13:497
|
// Price=500
|
13:498
|
// }
|
13:499
|
// }
|
13:500
|
//};
|
13:501
|
//context.Destinations.Add(firstDestination);
|
13:502
|
//await context.SaveChangesAsync();
|
13:503
|
//Console.WriteLine(
|
13:504
|
// $`DB populated: first destination id is {firstDestination.Id}`);
|
13:505
|
//Console.ReadKey();
|
13:506
| |
13:507
| |
13:508
|
Then, we need to load the entity into memory with a query, modify it, and call await SaveChangesAsync() to synchronize our changes with the database.
|
13:509
|
If we want to modify, say, just its description, a query such as the following is enough:
|
13:510
|
var toModify = await context.Destinations
|
13:511
|
.Where(m => m.Name == `Florence`).FirstOrDefaultAsync();
|
13:512
| |
13:513
| |
13:514
|
We need to load all the related destination packages that are not loaded by default. This can be done with the Include clause, as follows:
|
13:515
|
var toModify = await context.Destinations
|
13:516
|
.Where(m => m.Name == `Florence`)
|
13:517
|
.Include(m => m.Packages)
|
13:518
|
.FirstOrDefaultAsync();
|
13:519
| |
13:520
| |
13:521
|
After that, we can modify the description and package prices, as follows:
|
13:522
|
toModify.Description =
|
13:523
|
`Florence is a famous historical Italian town`;
|
13:524
|
foreach (var package in toModify.Packages)
|
13:525
|
package.Price = package.Price * 1.1m;
|
13:526
|
await context.SaveChangesAsync();
|
13:527
|
var verifyChanges= await context.Destinations
|
13:528
|
.Where(m => m.Name == `Florence`)
|
13:529
|
.FirstOrDefaultAsync();
|
13:530
|
Console.WriteLine(
|
13:531
|
$`New Florence description: {verifyChanges.Description}`);
|
13:532
|
Console.ReadKey();
|
13:533
| |
13:534
| |
13:535
| |
13:536
|
If entities included with the Include method themselves contain a nested collection we would like to include, we can use ThenInclude, as shown here:
|
13:537
|
.Include(m => m.NestedCollection)
|
13:538
|
.ThenInclude(m => m.NestedNestedCollection)
|
13:539
| |
13:540
|
Since Entity Framework always tries to translate each LINQ into a single SQL query, sometimes the resulting query might be too complex and slow. In such cases, starting from version 5, we can give Entity Framework the permission to split the LINQ query into several SQL queries, as shown here:
|
13:541
|
.AsSplitQuery().Include(m => m.NestedCollection)
|
13:542
|
.ThenInclude(m => m.NestedNestedCollection)
|
13:543
| |
13:544
|
Performance issues can be addressed by inspecting the SQL generated by a LINQ query with the help of the ToQueryString method:
|
13:545
|
var mySQL = myLinQQuery.ToQueryString ();
|
13:546
| |
13:547
|
Starting from version 5, the included nested collection can also be filtered with Where, as shown here:
|
13:548
|
.Include(m => m.Packages.Where(l-> l.Price < x))
|
13:549
| |
13:550
|
So far, we’ve performed queries whose unique purpose is to update the retrieved entities. Next, we will explain how to retrieve information that will be shown to the user and/or used by complex business operations.
|
13:551
|
Returning data to the presentation layer
|
13:552
|
To keep the layers separated and to adapt queries to the data that’s actually needed by each use case, DB entities aren’t sent as they are to the presentation layer. Instead, the data is projected into smaller classes that contain the information that’s needed by the use case. These are implemented by the presentation layer’s caller method. Objects that move data from one layer to another are called Data Transfer Objects (DTOs).
|
13:553
|
As an example, let’s create a DTO containing the summary information that is worth showing when returning a list of packages to the user (we suppose that, if needed, the user can get more details by clicking the package they are interested in):
|
13:554
| |
13:555
|
Let’s add a DTO to our WWTravelClubDBTest project that contains all the information that needs to be shown in a list of packages:
|
13:556
|
namespace WWTravelClubDBTest
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.