10 Entity Framework Core Hacks
--
Entity Framework Core (EF Core) is a powerful, lightweight, and extensible Object-Relational Mapper (ORM) for .NET applications. It simplifies data access by abstracting the complexities of working with relational databases, allowing developers to focus on writing application logic rather than dealing with low-level SQL queries. As EF Core continues to evolve, there are numerous lesser-known features and hacks that can significantly improve the efficiency and productivity of developers working with it.
In this article, I will show you 10 amazing Entity Framework Core hacks that you might not have known about. So, let’s get started!
1. Shadow Properties
Shadow Properties are properties that are not defined in your entity class but are included in the Entity Framework Core model. They can be used to store additional information about the entity without altering the entity class itself. Shadow properties can be useful for tracking metadata like “CreatedBy,” “ModifiedBy,” or “ModifiedDate” for an entity.
Defining a Shadow Property
public class ApplicationDbContext : DbContext
{
public DbSet<Book> Books { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Book>().Property<DateTime>("ModifiedDate");
}
}
public class Book
{
public int Id { get; set; }
public string Title { get; set; }
}
Using Shadow Properties in a Query
using (var context = new ApplicationDbContext())
{
var books = context.Books
.OrderByDescending(b => EF.Property<DateTime>(b, "ModifiedDate"))
.ToList();
}
2. Table-per-Hierarchy (TPH) Inheritance
One of the powerful features of Entity Framework Core is its support for various inheritance mapping strategies. In this section, we will dive into Table-per-Hierarchy (TPH) inheritance, which is the default inheritance strategy in EF Core. TPH inheritance allows you to map a class hierarchy to a single database table, providing an efficient and intuitive way to work with inheritance in your data models.