title
stringlengths 3
46
| content
stringlengths 0
1.6k
|
---|---|
13:57
|
For instance, Entity Framework Core passes all the changes that are performed on a DbContext instance to the database when you call the DbContext.SaveChangesAsync() method.
|
13:58
|
Changes that are passed to the database during a synchronization operation are executed in a single transaction. Moreover, for ORMs, such as Entity Framework Core, that have an explicit representation of transactions, if a synchronization operation is executed in the scope of a transaction then it uses that transaction instead of creating a new transaction.
|
13:59
|
The remaining sections in this chapter explain how to use Entity Framework Core, along with some example code based on this book’s WWTravelClub use case.
|
13:60
|
Configuring Entity Framework Core
|
13:61
|
Since, as detailed in Chapter 7, Understanding the Different Domains in Software Solutions, database handling is confined within a dedicated application layer, it is good practice to define your Entity Framework Core (DbContext) in a separate library. Accordingly, we need to define a .NET class library project.
|
13:62
|
We have two different kinds of library projects: .NET Standard and .NET Core. Please refer to Chapter 5, Implementing Code Reusability in C# 12, for a discussion on the various kinds of libraries.
|
13:63
|
While .NET libraries are tied to a specific .NET Core version, .NET Standard 2.0 libraries have a wide range of applications since they work with any .NET version greater than 2.0 and also with the old .NET Framework 4.7 and above.
|
13:64
|
Since our library is not a general-purpose library (it’s just a component of a specific .NET 8 application), instead of choosing a .NET Standard library project, we can simply choose a .NET 8 library. Our .NET 8 library project can be created and prepared as follows:
|
13:65
| |
13:66
|
Open Visual Studio, click Create new project and then select Class Library.
|
13:67
|
Name the new project WWTravelClubDB and accept the same name for the whole Visual Studio solution.
|
13:68
|
In the window that follows, choose .NET 8 as the target framework.
|
13:69
|
We must install all Entity Framework Core-related dependencies. The simplest way to have all the necessary dependencies installed is to add the NuGet package for the provider of the database engine we are going to use – in our case, SQL Server – as we mentioned in Chapter 10, Deciding on the Best Cloud-Based Solution.
|
13:70
|
In fact, any provider will install all the required packages since it has all of them as dependencies. So, let’s add the latest stable version of Microsoft.EntityFrameworkCore.SqlServer. If you plan to use several database engines, you can also add other providers since they can work side by side. Later in this chapter, we will install other NuGet packages that contain tools that we need to process our Entity Framework Core configuration.
|
13:71
|
Let’s rename the default Class1 class to MainDbContext. The Class1 class is automatically added to the class library. Now, let’s replace its content with the following code:
|
13:72
|
using System;
|
13:73
|
using Microsoft.EntityFrameworkCore;
|
13:74
|
namespace WWTravelClubDB
|
13:75
|
{
|
13:76
|
public class MainDbContext: DbContext
|
13:77
|
{
|
13:78
|
public MainDbContext(DbContextOptions options)
|
13:79
|
: base(options)
|
13:80
|
{
|
13:81
|
}
|
13:82
|
protected override void OnModelCreating(ModelBuilder
|
13:83
|
builder)
|
13:84
|
{
|
13:85
|
}
|
13:86
|
}
|
13:87
|
}
|
13:88
| |
13:89
| |
13:90
|
We inherit from DbContext, and we pass a DbContextOptions to the DbContext constructor. DbContextOptions contains creation options, such as the database connection string, which depends on the target DB engine.
|
13:91
|
All the collections that have been mapped to database tables will be added as properties of MainDbContext. The mapping configuration will be defined inside of the overridden OnModelCreating method with the help of the ModelBuilder object passed as a parameter.
|
13:92
| |
13:93
|
The next step is the creation of all the classes that represent the tables. These are called entities. We need an entity class for each DB table we want to map. Let’s create a Models folder in the project root for all of them. The next subsection explains how to define all the required entities.
|
13:94
|
Defining DB entities
|
13:95
|
DB design, like the whole application design, is organized in iterations (see Chapter 1, Understanding the Importance of Software Architecture). Let’s suppose that, in the first iteration, we need a prototype with two database tables: one for all the travel packages and another one for all the locations referenced by the packages. Each package covers just one location, while a single location may be covered by several packages, so the two tables are connected by a one-to-many relationship.
|
13:96
|
So, let’s start with the location database table. As we mentioned at the end of the previous section, we need an entity class to represent the rows of this table. Let’s call the entity class Destination:
|
13:97
|
namespace WWTravelClubDB.Models
|
13:98
|
{
|
13:99
|
public class Destination
|
13:100
|
{
|
13:101
|
public int Id { get; set; }
|
13:102
|
public required string Name { get; set; }
|
13:103
|
public required string Country { get; set; }
|
13:104
|
public string? Description { get; set; }
|
13:105
|
}
|
13:106
|
}
|
13:107
| |
13:108
|
In the code above, all the DB fields must be represented by read/write C# properties. Since both the Name and Country properties are obligatory but we are not going to define a constructor, we added the required keyword to instruct the compiler to signal an error whenever an instance is created without initializing them.
|
13:109
|
Suppose that each destination is something like a town or a region that can be defined by just its name and the country it is in and that all the relevant information is contained in its Description. In future iterations, we will probably add several more fields. Id is an auto-generated key.
|
13:110
|
However, now, we need to add information about how all the fields are mapped to DB fields. In Entity Framework Core, all the primitive types are mapped automatically to DB types by the DB engine-specific provider that’s used (in our case, the SQL Server provider).
|
13:111
|
Our only preoccupations are as follows:
|
13:112
| |
13:113
|
Length limits on the string: They can be taken into account by applying adequate MaxLength and MinLength attributes to each string property. All the attributes that are useful for the entity’s configuration are contained in the System.ComponentModel.DataAnnotations and System.ComponentModel.DataAnnotations.Schema namespaces. Therefore, it’s good practice to add both of them to all the entity definitions.
|
13:114
|
Specifying which fields are obligatory and which ones are optional: If the project is not using the new Nullable Reference Type feature, by default, all the reference types (such as all the strings) are assumed to be optional, while all the value types (numbers and GUIDs, for instance) are assumed to be obligatory. If we want a reference type to be obligatory, then we must decorate it with the Required attribute. On the other hand, if we want a T type property to be optional, and T is a value type, or the Nullable Reference Type feature is on, then we must replace T with T?. As a default, .NET 8 projects have the new Nullable Reference Type feature set.
|
13:115
|
Specifying which property represents the primary key: The key may be specified by decorating a property with the Key attribute. However, if no Key attribute is found, a property named Id (if there is one) is taken as the primary key. In our case, there is no need for the Key attribute.
|
13:116
| |
13:117
|
Since each destination is on one side of a one-to-many relationship, it must contain a collection of the related package entities; otherwise, it will be difficult to refer to the related entities in the clauses of our LINQ queries. This collection will have a fundamental role in our LINQ queries and will be populated by Entity Framework Core. However, as we will see later in this chapter, it must be ignored in most of the database update operations. Therefore, the best option to avoid compiler warnings is to assign them the null-forgiving fake default value: null!.
|
13:118
|
Putting everything together, the final version of the Destination class is as follows:
|
13:119
|
using System.Collections.Generic;
|
13:120
|
using System.ComponentModel.DataAnnotations;
|
13:121
|
using System.ComponentModel.DataAnnotations.Schema;
|
13:122
|
namespace WWTravelClubDB.Models
|
13:123
|
{
|
13:124
|
public class Destination
|
13:125
|
{
|
13:126
|
public int Id { get; set; }
|
13:127
|
[MaxLength(128)]
|
13:128
|
Public required string Name { get; set; }
|
13:129
|
[MaxLength(128)]
|
13:130
|
Public required string Country { get; set; }
|
13:131
|
public string? Description { get; set; }
|
13:132
|
public ICollection<Package> Packages { get; set; } = null!
|
13:133
|
}
|
13:134
|
}
|
13:135
| |
13:136
|
Since the Description property has no length limits, it will be implemented with a SQL Server nvarchar(MAX) field of indefinite length. We can write the code for the Package class in a similar way:
|
13:137
|
using System;
|
13:138
|
using System.ComponentModel.DataAnnotations;
|
13:139
|
using System.ComponentModel.DataAnnotations.Schema;
|
13:140
|
namespace WWTravelClubDB.Models
|
13:141
|
{
|
13:142
|
public class Package
|
13:143
|
{
|
13:144
|
public int Id { get; set; }
|
13:145
|
[MaxLength(128)]
|
13:146
|
Public required string Name { get; set; }
|
13:147
|
[MaxLength(128)]
|
13:148
|
public string? Description { get; set; }
|
13:149
|
public decimal Price { get; set; }
|
13:150
|
public int DurationInDays { get; set; }
|
13:151
|
public DateTime? StartValidityDate { get; set; }
|
13:152
|
public DateTime? EndValidityDate { get; set; }
|
13:153
|
public Destination MyDestination { get; set; } = null!
|
13:154
|
public int DestinationId { get; set; }
|
13:155
|
}
|
13:156
|
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.