An entity is a C# class that represents a business object and closely matches a database table. Each instance represents a record, while its properties represent data that Entity Framework Core (EF Core) can map to columns. In a code-first application, entity classes help define the database schema and provide the objects used for create, read, update, and delete (CRUD) operations. section 4.3.3 section 4.3.2
To add entities to a board-game API:
- Create classes for board games, domains, and mechanics. Use properties for their fields; attributes such as [Table], [Key], [Required], and [MaxLength] specify entity-specific mapping and constraints. section 4.3.3
- Create entity classes for the links between board games and their domains or mechanics. Configure each link’s two-property key in DbContext.OnModelCreating with the Fluent API. section 4.3.3
- Add navigation properties for related entities, then configure their relationships in OnModelCreating. Expose each entity type through a DbSet on the DbContext so application code can work with it. section 4.3.3
Reading and changing entities
For a GET request, a controller can obtain a DbContext, read board-game records as entities, and return the requested data in a JSON-serialized DTO. For an authorized rename request, it can read matching Mechanic entities, change their names, and let the DbContext track those changes. section 4.3.4
Listing 4.2 BoardGame.cs file
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace MyBGList.Models
{
[Table("BoardGames")] #1
public class BoardGame
{
[Key] #2
[Required]
public int Id { get; set; }
[Required]
[MaxLength(200)]
public string Name { get; set; } = null!;
[Required]
public int Year { get; set; }
[Required]
public int MinPlayers { get; set; }
[Required]
public int MaxPlayers { get; set; }
[Required]
public int PlayTime { get; set; }
[Required]
public int MinAge { get; set; }
[Required]
public int UsersRated { get; set; }
[Required]
[Precision(4, 2)]
public decimal RatingAverage { get; set; }
[Required]
public int BGGRank { get; set; }
[Required]
[Precision(4, 2)]
public decimal ComplexityAverage { get; set; }
[Required]
public int OwnedUsers { get; set; }
[Required]
public DateTime CreatedDate { get; set; }
[Required]
public DateTime LastModifiedDate { get; set; }
}
}
The BoardGame class shows how a concrete entity declares its table, key, required properties, and field constraints. section 4.3.3
EF Core can configure mapping through conventions, data annotations, or the Fluent API. Fluent API settings take precedence over annotations, which take precedence over conventions. With an empty database, code-first migrations can turn the configured entity model into a database schema; an existing database instead can be used to generate entity classes through scaffolding. section 4.3.3 section 4.3.2











