Module 4: Working with Data Using Entity Framework Core
Sections 4.4.1 and 4.4.2: Migrations and Database Schema Management
Entity Framework Core (EF Core) provides a robust mechanism for managing database schema changes through migrations. Migrations allow developers to evolve the database schema over time as the application requirements change, ensuring that the database stays in sync with the application's data models.
In this detailed explanation, we'll delve deeply into Sections 4.4.1 and 4.4.2:
- 4.4.1. Understanding Migrations
- Purpose of Migrations
- Migration Workflow
- 4.4.2. Creating and Applying Migrations
- Adding a Migration
- Applying Migrations
- Understanding Generated Migration Files
We'll cover concepts, workflows, detailed steps, and provide comprehensive code examples to ensure you have a solid grasp of managing migrations in EF Core.
4.4.1. Understanding Migrations
Purpose of Migrations
Migrations in EF Core serve to bridge the gap between your application's data model (defined via entity classes) and the actual database schema. As your application evolves—new features are added, existing ones modified, or outdated ones removed—the underlying data requirements change. Migrations help manage these changes systematically.
Key Purposes of Migrations:
- Schema Evolution: Manage changes in the database schema over time without losing existing data.
- Version Control: Track schema changes in source control alongside code changes, facilitating team collaboration.
- Automated Deployment: Simplify deploying schema changes to different environments (development, staging, production).
- Consistency: Ensure that different environments are in sync with the same schema version.
Migration Workflow
Understanding the migration workflow is essential to effectively managing database changes. The typical workflow involves the following steps:
-
Define or Modify Your Data Model:
- Create new entity classes or modify existing ones.
- Update relationships, constraints, and other configurations.
-
Add a Migration:
- Generate a migration script that captures the changes between the current model and the previous migration.
-
Review and Modify Migration Code (Optional):
- Sometimes, manual adjustments are needed to handle complex scenarios not automatically inferred.
-
Apply the Migration to the Database:
- Update the database schema based on the migration script.
- Apply all pending migrations to bring the database up to date.
-
Repeat as Necessary:
- Continue this cycle as the data model evolves.
Visual Representation of the Workflow:
Define/Modify Data Model --> Add Migration --> Review Migration Code --> Apply Migration --> Update Database
Important Concepts in Migration Workflow:
-
Model Snapshot:
- EF Core maintains a snapshot of the current model, allowing it to determine what changes have been made since the last migration.
- File Location: Typically found in
Migrations folder as YourDbContextModelSnapshot.cs.
-
Migration History Table:
- EF Core creates a table in your database, usually named
__EFMigrationsHistory, to keep track of applied migrations.
- Contains information about each applied migration, such as migration ID and product version.
4.4.2. Creating and Applying Migrations
This section covers the practical steps involved in generating and applying migrations using EF Core. We'll explore both the Add-Migration and Update-Database commands, how to use them via the Package Manager Console and .NET CLI, and understand the structure of the generated migration files.
Prerequisites
Before proceeding, ensure you've:
Adding a Migration
Adding a migration involves generating a migration script that captures the changes in your data model.
Using Package Manager Console (PMC):
-
Open PMC:
- In Visual Studio, navigate to
Tools > NuGet Package Manager > Package Manager Console.
-
Run the Add-Migration Command:
Add-Migration <MigrationName>
Using .NET CLI:
-
Open Terminal/CMD:
- Navigate to your project directory.
-
Run the Add Migration Command:
dotnet ef migrations add <MigrationName>
Result:
- A new folder named
Migrations is created (if it doesn't already exist) in your project.
- Inside the
Migrations folder, two main files are generated:
- Timestamp_MigrationName.cs
- Example:
20231010123456_InitialCreate.cs
- YourDbContextModelSnapshot.cs
- Example:
YourDbContextModelSnapshot.cs
File Structure Example:
YourProject/
│
├── Migrations/
│ ├── 20231010123456_InitialCreate.cs
│ └── YourDbContextModelSnapshot.cs
│
├── Data/
│ └── ApplicationDbContext.cs
│
├── Models/
│ ├── Product.cs
│ └── Category.cs
│
├── appsettings.json
│
└── Program.cs
Code Example of a Migration File (20231010123456_InitialCreate.cs):
using Microsoft.EntityFrameworkCore.Migrations;
namespace YourProject.Migrations
{
public partial class InitialCreate : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
// Creating the Categories table
migrationBuilder.CreateTable(
name: "Categories",
columns: table => new
{
CategoryId = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"), // Auto-incrementing primary key
Name = table.Column<string>(maxLength: 100, nullable: false),
Description = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Categories", x => x.CategoryId);
});
// Creating the Products table
migrationBuilder.CreateTable(
name: "Products",
columns: table => new
{
ProductId = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"), // Auto-incrementing primary key
Name = table.Column<string>(maxLength: 100, nullable: false),
Price = table.Column<decimal>(type: "decimal(18,2)", nullable: false),
CategoryId = table.Column<int>(nullable: false) // Foreign key
},
constraints: table =>
{
table.PrimaryKey("PK_Products", x => x.ProductId);
table.ForeignKey(
name: "FK_Products_Categories_CategoryId",
column: x => x.CategoryId,
principalTable: "Categories",
principalColumn: "CategoryId",
onDelete: ReferentialAction.Cascade); // Cascade delete
});
// Creating an index on CategoryId in Products table for performance
migrationBuilder.CreateIndex(
name: "IX_Products_CategoryId",
table: "Products",
column: "CategoryId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
// Dropping the Products table
migrationBuilder.DropTable(
name: "Products");
// Dropping the Categories table
migrationBuilder.DropTable(
name: "Categories");
}
}
}
Explanation:
-
Up Method:
- Defines the operations to apply when the migration is applied.
- Creates
Categories and Products tables with their respective columns, primary keys, foreign keys, and indexes.
-
Down Method:
- Defines how to revert the operations defined in the
Up method.
- Drops the
Products and Categories tables.
Model Snapshot (YourDbContextModelSnapshot.cs):
This file represents the current state of the model. EF Core uses it to compare against the model's current state to determine what changes need to be captured in future migrations.
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using YourProject.Data;
namespace YourProject.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
// Configuring model properties and relationships
modelBuilder
.HasAnnotation("ProductVersion", "6.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
modelBuilder.Entity("YourProject.Models.Category", b =>
{
b.Property<int>("CategoryId")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.HasKey("CategoryId");
b.ToTable("Categories");
});
modelBuilder.Entity("YourProject.Models.Product", b =>
{
b.Property<int>("ProductId")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<int>("CategoryId")
.HasColumnType("int");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<decimal>("Price")
.HasColumnType("decimal(18,2)");
b.HasKey("ProductId");
b.HasIndex("CategoryId");
b.ToTable("Products");
});
modelBuilder.Entity("YourProject.Models.Product", b =>
{
b.HasOne("YourProject.Models.Category", "Category")
.WithMany("Products")
.HasForeignKey("CategoryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
}
}
}
Key Points:
-
Entity Configuration:
- Each entity and its properties are defined, including data types, constraints, and relationships.
-
Change Tracking:
- By maintaining the snapshot, EF Core can detect changes and generate appropriate migration scripts.
File Path Examples:
Applying Migrations
Once you've created a migration, the next step is to apply it to your database. This updates the database schema to match your data model.
Using Package Manager Console (PMC):
-
Open PMC:
- In Visual Studio, go to
Tools > NuGet Package Manager > Package Manager Console.
-
Run the Update-Database Command:
Update-Database
- Applies all pending migrations to the database.
Using .NET CLI:
-
Open Terminal/CMD:
- Navigate to your project directory.
-
Run the Update Database Command:
dotnet ef database update
- Applies all pending migrations.
Applying a Specific Migration:
You can apply a specific migration and all preceding ones by specifying the migration name.
Verifying the Database Update:
After applying the migration, verify that your database has been updated accordingly.
Handling Multiple Migrations:
If multiple migrations are pending, running Update-Database will apply them in the order they were added, ensuring the database schema is sequentially updated.
Example: Adding and Applying Multiple Migrations
-
Add a New Migration:
Add-Migration AddSupplierEntity
Or via CLI:
dotnet ef migrations add AddSupplierEntity
-
Apply the Migration:
Update-Database
Or via CLI:
dotnet ef database update
Understanding Generated Migration Files
Migration files consist of C# code that defines the operations to apply and revert the schema changes. Understanding their structure is crucial for effective database management.
Components of a Migration File:
-
Migration Class:
- Each migration has a unique class that inherits from
Migration.
- Named based on the migration's name, often prefixed with a timestamp.
-
Up Method:
- Contains logic to apply the migration (e.g., creating tables, adding columns).
-
Down Method:
- Contains logic to revert the migration (e.g., dropping tables, removing columns).
Detailed Example: Adding a New Table (Supplier) Migration
Suppose we add a new entity Supplier to our data model:
Supplier Entity (Models/Supplier.cs):
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace YourProject.Models
{
public class Supplier
{
public int SupplierId { get; set; }
[Required, MaxLength(100)]
public string Name { get; set; }
public string ContactEmail { get; set; }
// Navigation property for many-to-many relationship with Product
public ICollection<Product> Products { get; set; }
}
}
Updated Product Entity (Models/Product.cs):
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace YourProject.Models
{
public class Product
{
public int ProductId { get; set; }
[Required, MaxLength(100)]
public string Name { get; set; }
public decimal Price { get; set; }
// Foreign key for Category
public int CategoryId { get; set; }
public Category Category { get; set; }
// Navigation property for many-to-many relationship with Supplier
public ICollection<Supplier> Suppliers { get; set; }
}
}
Adding the Migration:
Add-Migration AddSupplierEntity
Or via CLI:
dotnet ef migrations add AddSupplierEntity
Generated Migration File (20231010124500_AddSupplierEntity.cs):
using Microsoft.EntityFrameworkCore.Migrations;
namespace YourProject.Migrations
{
public partial class AddSupplierEntity : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
// Creating Suppliers table
migrationBuilder.CreateTable(
name: "Suppliers",
columns: table => new
{
SupplierId = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(maxLength: 100, nullable: false),
ContactEmail = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Suppliers", x => x.SupplierId);
});
// Creating the join table for many-to-many relationship between Products and Suppliers
migrationBuilder.CreateTable(
name: "ProductSupplier",
columns: table => new
{
ProductsProductId = table.Column<int>(nullable: false),
SuppliersSupplierId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ProductSupplier", x => new { x.ProductsProductId, x.SuppliersSupplierId });
table.ForeignKey(
name: "FK_ProductSupplier_Products_ProductsProductId",
column: x => x.ProductsProductId,
principalTable: "Products",
principalColumn: "ProductId",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ProductSupplier_Suppliers_SuppliersSupplierId",
column: x => x.SuppliersSupplierId,
principalTable: "Suppliers",
principalColumn: "SupplierId",
onDelete: ReferentialAction.Cascade);
});
// Creating index on SuppliersSupplierId for the join table
migrationBuilder.CreateIndex(
name: "IX_ProductSupplier_SuppliersSupplierId",
table: "ProductSupplier",
column: "SuppliersSupplierId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
// Dropping the join table
migrationBuilder.DropTable(
name: "ProductSupplier");
// Dropping the Suppliers table
migrationBuilder.DropTable(
name: "Suppliers");
}
}
}
Explanation:
Model Snapshot Update:
After adding the migration, the ModelSnapshot is updated to reflect the new state, including the Suppliers entity and the relationship with Products.
Reverting a Migration:
If you need to undo a migration, you can use the Update-Database command with the target migration name.
Advanced Considerations in Migrations
While the basic usage of migrations is straightforward, there are some advanced scenarios and best practices to consider:
-
Customizing Migration Operations:
- Sometimes, EF Core might not infer the desired schema changes accurately. You can manually edit the migration files to adjust the
Up and Down methods.
Example: Adding a Default Value to a Column
Suppose you want to add a new column IsActive to the Products table with a default value of true.
-
Update the Product Model:
public class Product
{
public int ProductId { get; set; }
// Other properties...
public bool IsActive { get; set; } = true; // New property
}
-
Add Migration:
Add-Migration AddIsActiveToProduct
Or via CLI:
dotnet ef migrations add AddIsActiveToProduct
-
Generated Migration File (20231010125000_AddIsActiveToProduct.cs):
using Microsoft.EntityFrameworkCore.Migrations;
namespace YourProject.Migrations
{
public partial class AddIsActiveToProduct : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "IsActive",
table: "Products",
type: "bit",
nullable: false,
defaultValue: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "IsActive",
table: "Products");
}
}
}
-
Review and Modify (if necessary):
- Ensure that the
defaultValue aligns with your requirements.
-
Handling Data Seeding:
- When adding seed data, ensure that the migration scripts include operations to insert the initial data.
Example: Seeding Categories
-
Update OnModelCreating in ApplicationDbContext:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Category>().HasData(
new Category { CategoryId = 1, Name = "Electronics", Description = "Electronic Items" },
new Category { CategoryId = 2, Name = "Books", Description = "Books and Literature" }
);
}
Applying Migrations in Team Environments
In collaborative development environments, managing migrations requires coordination to avoid conflicts and ensure consistency across different developers' local databases as well as deployment environments.
Strategies for Handling Migrations in Teams:
-
Centralize Migration Responsibility:
- Assign a specific team member or establish guidelines to manage when and how migrations are created to prevent conflicts.
-
Frequent Pulls and Merge:
- Regularly synchronize with the main branch to incorporate others’ migrations.
-
Avoid Long-Lived Feature Branches:
- Keep feature branches short or ensure they're frequently merged to reduce divergence in migrations.
-
Handle Conflicts Carefully:
- If multiple developers create migrations concurrently, manually resolve merge conflicts in migration files.
-
Consistent Environments:
- Ensure all team members are using similar EF Core and .NET versions to prevent version-related discrepancies in migrations.
Example Scenario:
- Developer A adds a
Supplier entity and creates migration AddSupplierEntity.
- Developer B adds a
Customer entity and creates migration AddCustomerEntity.
When both migrations are added to the same branch, EF Core manages them in the order they were added. If they affect the same area of the model, conflicts may occur, which must be resolved manually.
Comprehensive Code Example and File Paths
To cement the understanding, let's create a sample project structure and walk through the process of adding and applying migrations with thorough code examples.
1. Project Structure
Assume our project is named ProductCatalogApp. Here's the structure:
ProductCatalogApp/
│
├── Controllers/
│ ├── CategoriesController.cs
│ └── ProductsController.cs
│
├── Data/
│ ├── ApplicationDbContext.cs
│ └── Migrations/
│ ├── 20231010123456_InitialCreate.cs
│ ├── 20231010124500_AddSupplierEntity.cs
│ └── ApplicationDbContextModelSnapshot.cs
│
├── Models/
│ ├── Category.cs
│ ├── Product.cs
│ └── Supplier.cs
│
├── Views/
│ ├── Categories/
│ ├── Products/
│ └── Suppliers/
│
├── appsettings.json
│
├── Program.cs
│
└── ProductCatalogApp.csproj
2. Defining the DbContext (Data/ApplicationDbContext.cs)
using Microsoft.EntityFrameworkCore;
using YourProject.Models;
namespace YourProject.Data
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
// DbSet properties for entities
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<Supplier> Suppliers { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// Example Fluent API configuration
modelBuilder.Entity<Category>(entity =>
{
entity.HasKey(e => e.CategoryId);
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(100);
entity.Property(e => e.Description)
.HasMaxLength(500);
});
modelBuilder.Entity<Product>(entity =>
{
entity.HasKey(e => e.ProductId);
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(100);
entity.Property(e => e.Price)
.HasColumnType("decimal(18,2)");
entity.HasOne(e => e.Category)
.WithMany(c => c.Products)
.HasForeignKey(e => e.CategoryId);
});
modelBuilder.Entity<Supplier>(entity =>
{
entity.HasKey(e => e.SupplierId);
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(100);
entity.Property(e => e.ContactEmail)
.HasMaxLength(100);
});
// Configuring many-to-many relationship between Product and Supplier
modelBuilder.Entity<Product>()
.HasMany(p => p.Suppliers)
.WithMany(s => s.Products)
.UsingEntity<Dictionary<string, object>>(
"ProductSupplier",
j => j
.HasOne<Supplier>()
.WithMany()
.HasForeignKey("SupplierId")
.HasConstraintName("FK_ProductSupplier_Suppliers_SupplierId")
.OnDelete(DeleteBehavior.Cascade),
j => j
.HasOne<Product>()
.WithMany()
.HasForeignKey("ProductId")
.HasConstraintName("FK_ProductSupplier_Products_ProductId")
.OnDelete(DeleteBehavior.Cascade),
j =>
{
j.HasKey("ProductId", "SupplierId");
j.ToTable("ProductSupplier");
});
}
}
}
Explanation:
3. Defining Entity Models
Category (Models/Category.cs):
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace YourProject.Models
{
public class Category
{
public int CategoryId { get; set; }
[Required, MaxLength(100)]
public string Name { get; set; }
[MaxLength(500)]
public string Description { get; set; }
// Navigation property
public ICollection<Product> Products { get; set; }
}
}
Product (Models/Product.cs):
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace YourProject.Models
{
public class Product
{
public int ProductId { get; set; }
[Required, MaxLength(100)]
public string Name { get; set; }
public decimal Price { get; set; }
// Foreign key
public int CategoryId { get; set; }
// Navigation properties
public Category Category { get; set; }
public ICollection<Supplier> Suppliers { get; set; }
}
}
Supplier (Models/Supplier.cs):
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace YourProject.Models
{
public class Supplier
{
public int SupplierId { get; set; }
[Required, MaxLength(100)]
public string Name { get; set; }
[MaxLength(100)]
public string ContactEmail { get; set; }
// Navigation property
public ICollection<Product> Products { get; set; }
}
}
4. Configuring Dependency Injection and Connection String (Program.cs and appsettings.json)
Connection String (appsettings.json):
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=ProductCatalogDb;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
Dependency Injection Configuration (Program.cs):
using Microsoft.EntityFrameworkCore;
using YourProject.Data;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Configure DbContext with SQL Server provider
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
// Add controllers with views
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// HSTS, etc.
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
// Define the default route
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
Explanation:
-
Connection String:
- Specifies the database server and database name.
- Uses LocalDB for development purposes.
-
Dependency Injection:
- Registers
ApplicationDbContext with the service container.
- Specifies the use of SQL Server as the database provider, using the connection string from
appsettings.json.
5. Adding and Applying Migrations: A Comprehensive Example
Let's walk through adding the initial migration and applying it to the database.
Step 1: Adding the Initial Migration
-
Open Package Manager Console or Terminal:
- Visual Studio:
Tools > NuGet Package Manager > Package Manager Console
- Terminal: Navigate to
ProductCatalogApp directory.
-
Run the Add-Migration Command:
-
Result:
- Migration files
20231010123456_InitialCreate.cs and ApplicationDbContextModelSnapshot.cs are generated in the Migrations folder.
Generated Migration File (Migrations/20231010123456_InitialCreate.cs):
using Microsoft.EntityFrameworkCore.Migrations;
namespace YourProject.Migrations
{
public partial class InitialCreate : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
// Creating Categories table
migrationBuilder.CreateTable(
name: "Categories",
columns: table => new
{
CategoryId = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(maxLength: 100, nullable: false),
Description = table.Column<string>(maxLength: 500, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Categories", x => x.CategoryId);
});
// Creating Products table
migrationBuilder.CreateTable(
name: "Products",
columns: table => new
{
ProductId = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(maxLength: 100, nullable: false),
Price = table.Column<decimal>(type: "decimal(18,2)", nullable: false),
CategoryId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Products", x => x.ProductId);
table.ForeignKey(
name: "FK_Products_Categories_CategoryId",
column: x => x.CategoryId,
principalTable: "Categories",
principalColumn: "CategoryId",
onDelete: ReferentialAction.Cascade);
});
// Creating index on CategoryId in Products
migrationBuilder.CreateIndex(
name: "IX_Products_CategoryId",
table: "Products",
column: "CategoryId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
// Dropping Products table
migrationBuilder.DropTable(
name: "Products");
// Dropping Categories table
migrationBuilder.DropTable(
name: "Categories");
}
}
}
Step 2: Applying the Migration to the Database
-
Run the Update-Database Command:
-
Result:
- The
Categories and Products tables are created in the ProductCatalogDb SQL Server database.
Step 3: Verifying the Migration
Step 4: Adding a New Entity and Migration
Adding Supplier Entity:
-
Define the Supplier Model (Models/Supplier.cs):
- As shown in the previous section.
-
Update AppDbContext:
- Add
DbSet<Supplier> Suppliers { get; set; } to track the Supplier entity.
-
Configure the Many-to-Many Relationship:
- Done in
OnModelCreating via Fluent API.
-
Add Migration:
-
Generated Migration (Migrations/20231010124500_AddSupplierEntity.cs):
- As detailed in the previous example.
-
Apply the Migration:
-
Result:
Suppliers and ProductSupplier tables are created in the database.
Step 5: Adding Seed Data and Migration
Seeding Categories (OnModelCreating):
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// Existing configurations...
// Seed data for Categories
modelBuilder.Entity<Category>().HasData(
new Category { CategoryId = 1, Name = "Electronics", Description = "Electronic Items" },
new Category { CategoryId = 2, Name = "Books", Description = "Books and Literature" },
new Category { CategoryId = 3, Name = "Clothing", Description = "Apparel and Accessories" }
);
}
Add Migration for Seeding:
-
Generate the Migration:
-
Generated Migration (Migrations/20231010125000_SeedCategories.cs):
using Microsoft.EntityFrameworkCore.Migrations;
namespace YourProject.Migrations
{
public partial class SeedCategories : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.InsertData(
table: "Categories",
columns: new[] { "CategoryId", "Name", "Description" },
values: new object[,]
{
{ 1, "Electronics", "Electronic Items" },
{ 2, "Books", "Books and Literature" },
{ 3, "Clothing", "Apparel and Accessories" }
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DeleteData(
table: "Categories",
keyColumn: "CategoryId",
keyValue: 1);
migrationBuilder.DeleteData(
table: "Categories",
keyColumn: "CategoryId",
keyValue: 2);
migrationBuilder.DeleteData(
table: "Categories",
keyColumn: "CategoryId",
keyValue: 3);
}
}
}
-
Apply the Migration:
-
Result:
- The
Categories table is populated with the seeded data.
Step 6: Viewing Seeded Data
Conclusion
Sections 4.4.1 and 4.4.2 have been elaborated comprehensively, covering the purpose of migrations, the migration workflow, and the detailed process of creating and applying migrations with EF Core. Through step-by-step examples and code snippets, we've demonstrated how to manage database schema changes effectively, ensuring your application's data model remains synchronized with the underlying database.
Key Takeaways:
- Migrations are essential for evolving the database schema alongside your application.
- Add-Migration generates migration scripts based on model changes.
- Update-Database applies pending migrations to update the database schema.
- Migration Files contain
Up and Down methods that define how to apply and revert changes.
- Model Snapshot assists EF Core in tracking model changes.
- Best Practices include descriptive migration names, reviewing generated code, and coordinating in team environments.
By mastering migrations, you ensure that your application's data layer remains robust, maintainable, and in line with evolving business requirements.