Entity Framework Core: Getting Started in .NET

Abdullah SajjadAbdullah Sajjad
5 min read

Entity Framework Core (EF Core) is a modern, open-source, and cross-platform version of the popular Entity Framework data access technology. It serves as an object-relational mapper (O/RM), enabling .NET developers to work with a database using .NET objects, eliminating the need for most of the data-access code that typically needs to be written. EF Core supports many database engines, making it a versatile choice for data access in .NET applications.

What is EF Core?

EF Core is a lightweight, extensible, and cross-platform version of Entity Framework, designed to work with .NET Core applications. It allows developers to interact with databases using .NET objects, providing a higher level of abstraction over raw SQL queries. EF Core supports various database providers, including SQL Server, SQLite, PostgreSQL, MySQL, and more.

Why Use EF Core?

  1. Productivity: EF Core reduces the amount of boilerplate code required for data access, allowing developers to focus on business logic.

  2. Cross-Platform: It works seamlessly with .NET Core, making it suitable for applications running on Windows, macOS, and Linux.

  3. Flexibility: EF Core supports multiple database providers, enabling developers to switch databases with minimal code changes.

  4. Maintainability: By using EF Core, developers can maintain a clean separation between the data access layer and business logic, improving code maintainability.

Components of EF Core

DbContext

The DbContext class is a central part of EF Core. It represents a session with the database and is used to query and save instances of your entities. DbContext is responsible for managing the connection to the database, tracking changes to entities, and handling transactions.

Entity

An entity in EF Core is a class that maps to a table in the database. Each instance of the entity class corresponds to a row in the table. Entities are typically defined using plain C# classes and can include properties that map to columns in the database table.

Migrations

Migrations in EF Core provide a way to incrementally update the database schema to keep it in sync with the application's data model while preserving existing data. Migrations are created based on changes to the model and can be applied to the database to update its schema.

How to Set Up EF Core

Step-by-Step Guide

  1. Create a New Project:

     dotnet new console -o EFCoreExample
     cd EFCoreExample
    
  2. Install EF Core Packages:

     dotnet add package Microsoft.EntityFrameworkCore
     dotnet add package Microsoft.EntityFrameworkCore.SqlServer
     dotnet add package Microsoft.EntityFrameworkCore.Tools
    
  3. Define the Entity: Create a Entities folder and add the following classes:

     // Entities/Student.cs
     public class Student
     {
         public int StudentId { get; set; }
         public string FirstName { get; set; }
         public string LastName { get; set; }
         public DateTime EnrollmentDate { get; set; }
     }
    
     // Entities/Course.cs
     public class Course
     {
         public int CourseId { get; set; }
         public string Title { get; set; }
         public int Credits { get; set; }
     }
    
  4. Create the DbContext:

     // SchoolContext.cs
     using Microsoft.EntityFrameworkCore;
    
     public class SchoolContext : DbContext
     {
         public DbSet<Student> Students { get; set; }
         public DbSet<Course> Courses { get; set; }
    
         protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
         {
             optionsBuilder.UseSqlServer("YourConnectionStringHere");
         }
     }
    
  5. Add Migrations and Update Database:

     dotnet ef migrations add InitialCreate
     dotnet ef database update
    

Migrations

Migrations in EF Core provide a way to incrementally update the database schema to keep it in sync with the application's data model while preserving existing data.

Creating a Migration

To create a migration, you use the Add-Migration command in the Package Manager Console or the dotnet ef migrations add command in the terminal. This command generates a migration file that contains the code needed to update the database schema.

dotnet ef migrations add AddNewColumn

Applying Migrations

Migrations can be applied to the database using the Update-Database command in the Package Manager Console or the dotnet ef database update command in the terminal. This command executes the migration code to update the database schema.

dotnet ef database update

Generating SQL Scripts

EF Core allows you to generate SQL scripts for migrations using the Script-Migration command in the Package Manager Console or the dotnet ef migrations script command in the terminal. This is useful for scenarios where you need to apply migrations manually or in a production environment.

dotnet ef migrations script

Configuring EF Core

EF Core can be configured using the OnModelCreating method in the DbContext class or through data annotations in the model classes.

Using Fluent API

The Fluent API is used to configure EF Core behavior and mappings using code. It provides a way to specify relationships, constraints, and other configurations in a fluent, readable manner.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Student>()
        .Property(s => s.FirstName)
        .IsRequired();
}

Using Data Annotations

Data annotations are attributes that can be applied to entity classes and properties to configure EF Core behavior. They provide a simple way to specify mappings and constraints directly in the model classes.

public class Student
{
    public int StudentId { get; set; }

    [Required]
    public string FirstName { get; set; }

    public string LastName { get; set; }
    public DateTime EnrollmentDate { get; set; }
}

Basic Operations

Create

To create a new entity, you add it to the DbSet and call SaveChanges on the DbContext.

using (var context = new SchoolContext())
{
    var student = new Student { FirstName = "John", LastName = "Doe", EnrollmentDate = DateTime.Now };
    context.Students.Add(student);
    context.SaveChanges();
}

Read

To read entities, you use LINQ queries on the DbSet to retrieve data from the database.

using (var context = new SchoolContext())
{
    var students = context.Students.ToList();
}

Update

To update an entity, you modify its properties and call SaveChanges on the DbContext.

using (var context = new SchoolContext())
{
    var student = context.Students.First();
    student.LastName = "Smith";
    context.SaveChanges();
}

Delete

To delete an entity, you remove it from the DbSet and call SaveChanges on the DbContext.

using (var context = new SchoolContext())
{
    var student = context.Students.First();
    context.Students.Remove(student);
    context.SaveChanges();
}

EF Core simplifies data access in .NET applications by providing a high-level abstraction over database operations. By following the steps outlined above, you can set up EF Core, configure it, and perform basic CRUD operations in your .NET applications.

0
Subscribe to my newsletter

Read articles from Abdullah Sajjad directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Abdullah Sajjad
Abdullah Sajjad

Full Stack - Best in Products’ Dashboards | Next.js - React Native - Typescript - C# - .NET Web APIs - Web3 | Empowering Businesses with Technology - Remote