EF Core Notes with Examples
DbContext:
The
primary class responsible for interacting with the database in EF Core.
Acts as a
bridge between the database and the application, tracking changes and
coordinating data retrieval.
Contains
DbSets for each entity type in the model.
Example:
public async Task
AddProduct(AppDbContext context)
{
var
product = new Product
{
Name = "Laptop",
Price = 1200.00m
};
context.Products.Add(product);
await context.SaveChangesAsync();
Console.WriteLine("Product added!");
}
DbSet:
Represents
a collection of entities of a specific type in the context of the database.
Allows
querying, adding, updating, and deleting entities.
Maps to a
table in the database.
Example:
using
Microsoft.EntityFrameworkCore;
public class
AppsDbContext : DbContext
{
public
AppsDbContext(DbContextOptions<AppsDbContext> options) : base(options){
}
public DbSet<Post> Posts
{get; set;}
public DbSet<Category>
Categories{get;set;}
protected override void
OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Post>()
.Property(p
=>p.CreatedDate)
.HasColumnType("datetime");
}
}
Explanations:
The AppsDbContext
class extends DbContext, acting as a bridge between the application and the
database.
It contains
DbSet<Post> and DbSet<Category> properties, representing the Post
and Category tables in the database.
The constructor
accepts DbContextOptions to configure the context.
Models/Entities:
Classes
that represent the structure of data in the database.
Each model
corresponds to a table, and its properties correspond to columns.
Often
annotated with data annotations or configured using the Fluent API to define
relationships and constraints.
Example:
public class
Student
{
[Key]
public int StudentId { get; set; }
[Required]
public string Name { get; set; }
//
Navigation property to related Courses
public ICollection<Course> Courses { get; set; }
}
Explanation:
Student class
represents a table with StudentId and Name columns.
Course Table:
Each course will have a StudentId foreign key linking back to the Student
table.
Each Student can
have multiple associated Courses.
Migrations:
A way to
manage changes to the database schema over time.
EF Core
generates migration scripts based on changes to the model classes.
Migrations
can be applied to the database to update its schema to match the current model.
Example:
When we have an
initial model, and want to manage changes to the schema (like adding a new
column) using migrations.
1. Initial Model
You start with a
simple Student model.
public class
Student
{
[Key]
public int StudentId { get; set; }
[Required]
public string Name { get; set; }
}
At this point,
the Student table in database only has StudentId and Name columns.
2. Add a New
Property to the Model
Now wants to add
a DateOfBirth property to the Student model.
public class
Student
{
[Key]
public int StudentId { get; set; }
[Required]
public string Name { get; set; }
public DateTime DateOfBirth { get; set; } // New property
}
3. Create a
Migration
Once modified the
model, use EF Core's migration system to update the database schema.
dotnet ef
migrations add AddDateOfBirthToStudent
This will
generate a migration file (located in the Migrations folder) that looks like
this:
public partial
class AddDateOfBirthToStudent : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<DateTime>(
name: "DateOfBirth",
table: "Students",
nullable: false,
defaultValue: new DateTime(2000, 1, 1)); //
Default value
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "DateOfBirth",
table: "Students");
}
}
Up(): Specifies
the changes to be applied (adding the DateOfBirth column).
Down(): Defines
how to revert the changes (removing the DateOfBirth column).
4. Apply the
Migration
To apply the
migration and update the database schema, use:
.NET CLI:
dotnet ef
database update
This command will
update database schema by adding the DateOfBirth column to the Students table.
5. Verify the
Changes
Now, if you look
at the Students table in the database, you’ll see a new column DateOfBirth has
been added.
Final steps:
Initial state:
Your Student table has StudentId and Name columns.
Change: You add a
DateOfBirth property to the Student class.
Migration: The
Add-Migration command generates a migration script.
Apply: The
Update-Database command updates the database schema.
This process
allows you to track changes to your data model and synchronize them with the
database schema over time.
LINQ Queries:
Language
Integrated Query (LINQ) allows querying of the database using C# syntax.
Enables
powerful, readable queries against data models.
Can be
used with DbSet to fetch, filter, order, and group data.
Example:
using (var
dbContext = new MyDbContext())
{
//
Fetch all students
var
allStudents = dbContext.Students.ToList();
//
Filter students with name "John"
var
johnStudents = dbContext.Students.Where(s => s.Name ==
"John").ToList();
//
Order students by name
var
orderedStudents = dbContext.Students.OrderBy(s => s.Name).ToList();
//
Group students by age
var
studentsGroupedByAge = dbContext.Students.GroupBy(s => s.Age).Select(g =>
new{
Age = g.Key, Students = g.ToList()
}).ToList();
//
Fetch students and their courses
var
studentsWithCourses = dbContext.Students.Select(s => new{
s.Name,
Courses = s.Courses.Select(c => c.CourseName).ToList()
}).ToList();
//
Display students with their courses
foreach (var student in studentsWithCourses)
{
Console.WriteLine($"Student: {student.Name}");
Console.WriteLine("Courses: " + string.Join(",
", student.Courses));
}
}
Explanations:
Fetch all
students: ToList() fetches all records.
Filter students:
Where() filters based on a condition (Name == "John").
Order students:
OrderBy() sorts based on a field (Name).
Group students:
GroupBy() groups students by a property (Age).
Fetch students
with courses: Select() is used to project the data into a new shape (students
with their courses).
Each query
interacts with the database using LINQ, making the code clean, readable, and
easy to understand.
Comments
Post a Comment