title
stringlengths 3
46
| content
stringlengths 0
1.6k
|
---|---|
13:257
|
}
|
13:258
| |
13:259
|
Together with the two configuration classes:
|
13:260
|
using Microsoft.EntityFrameworkCore;
|
13:261
|
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
13:262
|
namespace WWTravelClubDB.Models
|
13:263
|
{
|
13:264
|
internal class DestinationConfiguration :
|
13:265
|
IEntityTypeConfiguration<Destination>
|
13:266
|
{
|
13:267
|
public void Configure(EntityTypeBuilder<Destination> builder)
|
13:268
|
{
|
13:269
|
builder
|
13:270
|
.HasIndex(m => m.Country);
|
13:271
|
builder
|
13:272
|
.HasIndex(m => m.Name);
|
13:273
|
}
|
13:274
|
}
|
13:275
|
}
|
13:276
|
using Microsoft.EntityFrameworkCore;
|
13:277
|
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
13:278
|
namespace WWTravelClubDB.Models
|
13:279
|
{
|
13:280
|
internal class PackageConfiguration : IEntityTypeConfiguration<Package>
|
13:281
|
{
|
13:282
|
public void Configure(EntityTypeBuilder<Package> builder)
|
13:283
|
{
|
13:284
|
builder
|
13:285
|
.HasIndex(m => m.Name);
|
13:286
|
builder
|
13:287
|
.HasIndex(nameof(Package.StartValidityDate),
|
13:288
|
nameof(Package.EndValidityDate));
|
13:289
|
}
|
13:290
|
}
|
13:291
|
}
|
13:292
| |
13:293
|
I prefer to define just general configuration and relationships in the context class. It is also convenient to use data annotation just for restricting property values (maximum and minimum length, required fields, and so on). This way, entities don’t depend on the specific ORM used and can be exported outside of the data layer, if needed.
|
13:294
|
The best place for other entity-specific configurations is the configuration class. I also avoid using the EntityTypeConfiguration attribute and call entity configuration classes from within the context class since this attribute ties the entity to a specific ORM.
|
13:295
|
The previous example shows a one-to-many relationship, but Entity Framework Core 8 also supports many-to-many relationship:
|
13:296
|
modelBuilder
|
13:297
|
.Entity<Teacher>()
|
13:298
|
.HasMany(e => e.Classrooms)
|
13:299
|
.WithMany(e => e.Teachers)
|
13:300
| |
13:301
|
In the preceding case, the join entity and the database join table are created automatically, but you can also specify an existing entity as the join entity. In the previous example, the join entity might be the course that the teacher teaches in each classroom:
|
13:302
|
modelBuilder
|
13:303
|
.Entity<Teacher>()
|
13:304
|
.HasMany(e => e.Classrooms)
|
13:305
|
.WithMany(e => e.Teachers)
|
13:306
|
.UsingEntity<Course>(
|
13:307
|
b => b.HasOne(e => e.Teacher).WithMany()
|
13:308
|
.HasForeignKey(e => e.TeacherId),
|
13:309
|
b => b.HasOne(e => e.Classroom).WithMany()
|
13:310
|
.HasForeignKey(e => e.ClassroomId));
|
13:311
| |
13:312
|
Once you’ve configured Entity Framework Core, we can use all the configuration information we have to create the actual database and put all the tools we need in place in order to update the database’s structure as the application evolves. The next section explains how.
|
13:313
|
Entity Framework Core migrations
|
13:314
|
Now that we’ve configured Entity Framework and defined our application-specific DbContext subclass, we can use the Entity Framework Core design tools to generate the physical database and create the database structure snapshot that’s needed by Entity Framework Core to interact with the database.
|
13:315
|
Entity Framework Core design tools must be installed in each project that needs them as NuGet packages. There are two equivalent options:
|
13:316
| |
13:317
|
Tools that work in any operating system console: These are available through the Microsoft.EntityFrameworkCore.Design NuGet package. All Entity Framework Core commands are in dotnet ef ..... format since they are contained in the ef command line’s .NET Core application.
|
13:318
|
Tools that are specific to the Visual Studio Package Manager Console: These are contained in the Microsoft.EntityFrameworkCore.Tools NuGet package. They don’t need the dotnet ef prefix since they can only be launched from the Package Manager Console inside Visual Studio.
|
13:319
| |
13:320
|
Entity Framework Core’s design tools are used within the design/update procedure. This procedure is as follows:
|
13:321
| |
13:322
|
We modify DbContext and the entities’ definitions as needed.
|
13:323
|
We launch the design tools to ask Entity Framework Core to detect and process all the changes we made.
|
13:324
|
Once launched, the design tools update the database structure snapshot and generate a new migration, that is, a file containing all the instructions we need in order to modify the physical database to reflect all the changes we made.
|
13:325
|
We launch another tool to update the database with the newly created migration.
|
13:326
|
We test the newly configured DB layer, and if new changes are necessary, we go back to step 1.
|
13:327
|
When the data layer is ready, it is deployed in staging or production, where all the migrations are applied once more to the actual staging/production database.
|
13:328
| |
13:329
|
This is repeated several times in the various software project iterations and during the lifetime of the application.
|
13:330
|
If we operate on an already existing database, we need to configure DbContext and its models to reflect the existing structure of all the tables we want to map. This can be done automatically with the Scaffold-DbContext command (see https://learn.microsoft.com/en-us/ef/core/managing-schemas/scaffolding/?tabs=vs for more details).
|
13:331
|
All classes generated by .NET are partial classes, so the user can enrich them with further methods without modifying the scaffolded classes by adding the new methods to partial classes with the same names.
|
13:332
|
Then, if we want to start using migration instead of continuing with direct database changes, we can call the design tools with the IgnoreChanges option so that they generate an empty migration. Also, this empty migration must be passed to the physical database so that it can synchronize a database structure version associated with the physical database with the version that’s been recorded in the database snapshot. This version is important because it determines which migrations must be applied to a database and which ones have already been applied.
|
13:333
|
However, developers may also choose to continue manually modifying the database and repeating the scaffold operation after each change.
|
13:334
|
The whole design process needs a test/design database, and if we operate on an existing database, the structure of this test/design database must reflect the actual database – at least in terms of the tables we want to map. To enable design tools so that we can interact with the database, we must define the DbContextOptions options that they pass to the DbContext constructor. These options are important at design time since they contain the connection string of the test/design database. The design tools can be informed about our DbContextOptions options if we create a class that implements the IDesignTimeDbContextFactory<T> interface, where T is our DbContext subclass:
|
13:335
|
using Microsoft.EntityFrameworkCore;
|
13:336
|
using Microsoft.EntityFrameworkCore.Design;
|
13:337
|
namespace WWTravelClubDB
|
13:338
|
{
|
13:339
|
public class LibraryDesignTimeDbContextFactory
|
13:340
|
: IDesignTimeDbContextFactory<MainDbContext>
|
13:341
|
{
|
13:342
|
private const string connectionString =
|
13:343
|
@`Server=(localdb)mssqllocaldb;Database=wwtravelclub;
|
13:344
|
Trusted_Connection=True;MultipleActiveResultSets=true`;
|
13:345
|
public MainDbContext CreateDbContext(params string[] args)
|
13:346
|
{
|
13:347
|
var builder = new DbContextOptionsBuilder<MainDbContext>();
|
13:348
| |
13:349
|
builder.UseSqlServer(connectionString);
|
13:350
|
return new MainDbContext(builder.Options);
|
13:351
|
}
|
13:352
|
}
|
13:353
|
}
|
13:354
| |
13:355
|
connectionString will be used by Entity Framework to create a new database in the local SQL Server instance that’s been installed in the development machine and connects with Windows credentials. You are free to change it to reflect your needs.
|
13:356
|
Now, we are ready to create our first migration! Let’s get started:
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.