Features of Entity Framework Core

Overview

What can we achieve with EF Core? EF Core provides numerous features. The illustration below highlights some of these features:

Models

EF Core accesses data via models. The following two distinct components make up the models:

  • Entity type classes
  • DbContext class

Entity type classes

An entity is a uniquely identifiable object such as a person, school or a concept. Entity type classes are classes that map to a database table. Let’s look at some examples.

The code below defines a Book entity type class:

Press + to interact
public class Book
{
public int Id { get; set; }
public string Title { get; set; }
public decimal Price { get; set; }
}

The code below defines a Category entity type class:

Press + to interact
public class Category
{
public int Id { get; set; }
public string Title { get; set; }
public List<Book> Books { get; set; }
}

DbContext class

The DbContext class represents a session with the database. It manages the interactions with the database. These interactions include the following:

  • Connection management
  • Querying
  • Saving
  • Model configuration
  • Change tracking
  • Caching
  • Transaction management

Within the DbContext class, each entity type is exposed as a DbSet<TEntity> property, where TEntity represents an entity type. This DbSet<TEntity> property represents a collection for a given entity within the DbContext and is the gateway to database operations against that entity.

To implement the DbContext class in an application, we need to create a class that derives from the DbContext class. Below is an example of such a class:

Press + to interact
public class BooksContext : DbContext
{
//entities
public DbSet<Book> Books { get; set; }
public DbSet<Category> Categories { get; set; }
}

In this example, BooksContext has two DbSet<TEntity> properties. The first represents a collection of Book entities mapped by convention to a database table named Books. The second DbSet<TEntity> property represents a collection of Category entities mapped to a table named Categories.

Once instantiated, this BooksContext class connects to the database and can save or retrieve Book and Category data.

Querying data

EF Core simplifies data querying. It retrieves instances of entity types from the database through a programming model called LINQ. LINQ stands for Language Integrated Query. Below is an example:

Press + to interact
using (var db = new BooksContext())
{
var books = db.Books
.Where(b => b.Price > 3000)
.ToList();
}

This example outputs a collection of books that cost over $3,000.

Saving data

EF Core uses instances of the entity type classes to create, modify, and delete data in the database. Below is an example:

Press + to interact
using (var db = new BooksContext())
{
var book = new Book { Title= "Learning Entity Framework Core", Price=3000 };
db.Books.Add(book);
db.SaveChanges();
}

Here, an instance of the BooksContext saves the Book entity type into the database.

Change tracking

Each DbContext instance tracks changes made to entities. Every entity is associated with a given EntityState. The new Book entity is in the Added state at line 4 in the code snippet above. In this state, an entity type is attached to the DbContext, but is not inserted into the database, using the command below:

Press + to interact
db.Books.Add(book);

On line 5, the SaveChanges method saves the Book entity into the database by using the following command:

Press + to interact
db.SaveChanges();

Logging

EF Core contains several mechanisms for generating logs. For instance, we can log onto the console by overriding the OnConfiguring method of the DbContext class, as shown below:

Press + to interact
public class BooksContext : DbContext
{
...
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.LogTo(Console.WriteLine);
}

Logs are great for debugging. They provide insight into what’s going on behind the scenes.

Managing database schemas

EF Core provides two workflows for keeping the model in sync with the database schema.

  • Reverse Engineering: This workflow involves scaffolding a model from a database schema. It is a Database First workflow because the database schema is the source of truth.

Reverse engineering uses table information to create entity type classes, column information to define the class properties, and foreign keys for relationships among the entities. Reverse engineering is performed using the dotnet ef dbcontext scaffold command.

  • Code First: This workflow uses the EF Core model as the source of truth. Migration files keep a record of changes to the model. These files update the database schema. For this reason, this workflow is also called Migrations.

In this course, we’ll demonstrate various EF Core features through code samples. The business logic used in the code samples is from a fictitious music artists company. This company has a database with tables such as the following:

  • Employees table: Stores the music artists’ names and ages
  • Studios table: Stores the studio addresses where the music artists work
  • Albums table: Stores the titles of the albums released by the music artists.
  • Tags table: Stores the categories of the albums