liveBook · Manning

Entity

As explained in ASP.NET Core in Action, 3e

An entity is an application object whose structure and identity are mapped by an object-relational mapper to a database record.

An entity is a .NET POCO class that EF Core maps to a database table. Its properties represent stored columns, and each object represents a database row. A DbContext discovers entities exposed through DbSet<T> properties and builds an internal data model, including linked entities and their relationships. section 12.1.4 section 12.6

Working with an entity typically involves:

  • Define a POCO class using EF Core conventions, such as an Id-suffixed property for a primary key. section 12.2.2
  • Represent relationships with navigation collections and foreign-key properties; Recipe and Ingredient form a many-to-one relationship. section 12.1.4 section 12.2.2
  • Create and track entity objects through DbContext, then call SaveChangesAsync to insert their rows. section 12.4.1

Recipe and Ingredient entities

A cooking API can define Recipe with RecipeId, Name, Method, and an ICollection<Ingredient>. Ingredient can define IngredientId, RecipeId, Name, Quantity, and Unit. Creating a Recipe together with its Ingredients lets EF Core generate the linked database rows and foreign-key values. section 12.2.2 section 12.4.1

Listing 12.2 Defining the EF Core entity classes
public class Recipe
{
    public int RecipeId { get; set; }
    public required string Name { get; set; }
    public TimeSpan TimeToCook { get; set; }
    public bool IsDeleted { get; set; }
    public required string Method { get; set; }
    public required ICollection<Ingredient> Ingredients { get; set; }   #1
}
public class Ingredient
{
    public int IngredientId { get; set; }
    public int RecipeId { get; set; }
    public required string Name { get; set; }
    public decimal Quantity { get; set; }
    public required string Unit { get; set; }
}

Inspect the compact Recipe and Ingredient class definitions, including keys, scalar properties, and the navigation collection. section 12.2.2

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains class mapping, conventions, relationships, model discovery, and insertion, while deferring many convention details and customizations.
Examples
Demonstrates Recipe and Ingredient classes, a many-to-one relationship, and creating linked rows through a recipe service.
What you can do after
Build it from scratch by defining entity classes, exposing them through DbContext, tracking objects, and saving mapped rows.
How it connects
Connects entities with ORM, DbContext, database tables, primary keys, foreign keys, relationships, and migrations.

Also explained in

Compare how 12 books explain entity →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.