In this lesson, you will learn how to structure your C# classes so Entity Framework Core automatically recognizes them as database tables without needing explicit configuration.
The Power of "Convention over Configuration"
EF Core is designed to be "smart" by default. Instead of forcing you to write lines of mapping code for every single property, the framework looks for standard naming and structural patterns in your POCO (Plain Old CLR Object) classes. If your classes follow these established "conventions," EF Core builds your database schema automatically.
The Key Requirements
To participate in automatic entity discovery, your class must meet two primary criteria:
- Public Properties: The class must expose public properties with
getandsetaccessors. EF Core ignores private fields or methods. - A Primary Key: EF Core needs a way to identify unique rows. The convention is simple: a property named
Idor<ClassName>Id(case-insensitive) will be automatically promoted to the Primary Key.
Consider this Product class:
public class Product
{
// EF Core discovers this as the Primary Key
public int Id { get; set; }
// EF Core maps these to columns
public string Name { get; set; }
public decimal Price { get; set; }
}
When you add a DbSet<Product> Products to your DbContext, EF Core scans the Product class. Because it finds an Id property, it maps the class to a table named Products (pluralized by default) and treats Id as the clustered primary key.
Why this matters
By adhering to these naming conventions, you keep your DbContext clean and focused on your business logic rather than boilerplate mapping code. You only need to move beyond these conventions when your database schema requires special constraints, non-standard naming, or complex relationships that the defaults cannot infer.
Think of conventions as the "happy path"—when your domain model follows the standard design, the framework does the heavy lifting for you, allowing you to focus on application behavior rather than infrastructure plumbing.
Key Takeaway: EF Core automatically maps classes to database tables if they contain public properties and follow naming conventions for primary keys, specifically by using a property named Id or [ClassName]Id.