Sub topic 3
Defining Entity Classes
An entity class is a plain C# class that EF Core maps to a database table. Each object of the class stands for one row in that table. Each property stands for one column. This chapter shows you how to write entity classes and how EF Core reads them.
What an Entity Is
A class is a template for objects in C#. Most classes in your program never touch a database. A class becomes an entity when EF Core knows about it and maps it to a table.
You do not need a special base class or interface. An entity is a normal class with public properties. This is why people call EF Core entities "POCOs." A POCO is a "plain old CLR object": a class that does not depend on any framework.
Here is the basic mapping:
| C# side | Database side |
|---|---|
| Entity class (`Blog`) | Table (`Blogs`) |
| Object (`new Blog { ... }`) | Row |
| Property (`Url`) | Column (`Url`) |
| Key property (`BlogId`) | Primary key column |
| Foreign key property (`Post.BlogId`) | Foreign key column |
Conventions: Rules EF Core Follows for You
A convention is a default rule that EF Core applies when you have not configured something yourself. With conventions you can write a working model with no extra setup. These are the main ones:
- Mapped properties. EF Core maps every public property that has both a getter and a setter.
- Primary key. A primary key is the column that uniquely identifies each row. EF Core picks a property named
Idor<ClassName>Idas the key. For example,BlogIdis the key ofBlog. Case does not matter, soIDalso works. - Generated keys. When the key is an
intorlong, the database creates the value for each new row (1, 2, 3, and so on). You do not set it yourself. - Table names. In the next chapter you will expose each entity through a
DbSetproperty on your context. EF Core names the table after that property, such asBlogs. - Required or optional. A nullable type (
string?,int?) becomes a column that allows NULL. A non-nullable type (string,int) becomes aNOT NULLcolumn. Forstring, this depends on nullable reference types. That C# feature is on by default in new projects.
A Worked Example: Blogs and Posts
Create a file named Model.cs in your project and add these two classes:
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; } = "";
public List<Post> Posts { get; } = new();
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; } = "";
public string Content { get; set; } = "";
public int BlogId { get; set; }
public Blog Blog { get; set; } = null!;
}Here is how EF Core reads this code:
BlogIdandPostIdfollow the key naming rule, so they become primary keys.Url,Title, andContentare non-nullable strings, so they become required text columns.Blog.Postsis a navigation property: a property that points to related entities instead of holding a plain value. A blog can have many posts.Post.Blogis also a navigation property. It points back to the one blog that owns the post.Post.BlogIdis a foreign key: a column that stores the key of a row in another table. EF Core spots it because its name joins the navigation name (Blog) and the key name ofBlog(BlogId).
Why `= ""` and `= null!`?
Nullable reference types make the compiler warn you when a non-nullable property could be left empty. Writing = "" gives each string a safe starting value.
The Blog navigation is different. EF Core fills it in when it loads a post together with its blog. Writing = null! tells the compiler, "Trust me, this will be set." The ! hides the warning but does not create an object. If you read post.Blog before EF Core has loaded it, the value is still null.
Why does `Posts` have no setter?
EF Core can fill a collection navigation through its getter. Creating the list right away with = new() means blog.Posts.Add(...) never fails with a null error. This pattern is common and safe.
How C# Types Become Column Types
Each database provider picks a column type for each C# type. This table shows common choices for SQLite, the provider used in this tutorial:
| C# type | SQLite column type | Allows NULL? |
|---|---|---|
| `int`, `long`, `bool` | INTEGER | No |
| `int?`, `bool?` | INTEGER | Yes |
| `double` | REAL | No |
| `string` | TEXT | No |
| `string?` | TEXT | Yes |
| `decimal` | TEXT | No |
| `DateTime` | TEXT | No |
| `Guid` | TEXT | No |
Other providers, such as SQL Server or PostgreSQL, use their own types. Your C# code stays the same.
A Richer Entity
This class uses several property types and one property that EF Core skips:
public class Product
{
public int Id { get; set; }
public string Name { get; set; } = "";
public string? Description { get; set; }
public decimal Price { get; set; }
public bool IsActive { get; set; }
public DateTime CreatedAt { get; set; }
public int? StockCount { get; set; }
// Not mapped: it has only a getter and is computed from other values.
public string Label => $"{Name} ({Price:C})";
}Idis the key, because its name matches the rule.DescriptionandStockCountare optional columns, because their types are nullable.Labelhas no setter, so EF Core does not create a column for it. You can still use it in your C# code.
Common Mistakes and Edge Cases
- No key. If a class has no property named
Idor<ClassName>Id, EF Core stops with an error like "The entity type 'Product' requires a primary key to be defined." Rename the property, or configure the key yourself (covered in a later chapter). - Misspelled key.
ProductIDworks because case does not matter.ProdIddoes not match the rule, so it is not picked as the key. - Fields instead of properties.
public string Name;is a field, not a property. EF Core does not map public fields by convention. Always use{ get; set; }. - Two keys. A primary key made of two columns is called a composite key. Conventions cannot create one. You need the Fluent API for that.
- Guid keys. For a
Guidkey, EF Core creates the value in your program when you add the entity. The database does not create it. - Unloaded navigations. A navigation property is empty or
nulluntil EF Core loads the related data. A later chapter shows how to load it.
Exercises
Exercise
You write a class Customer with properties CustomerNumber (int), Name (string), and Email (string?). EF Core reports that Customer has no primary key. Why, and what is the simplest fix?
Show answer
EF Core only treats a property named Id or CustomerId (any letter case) as the key by convention. CustomerNumber matches neither name. The simplest fix is to rename it to Id or CustomerId. You could also configure CustomerNumber as the key yourself, which a later chapter covers.
Exercise
In the Product class, which columns can hold NULL, and which property gets no column at all?
Show answer
Description (string?) and StockCount (int?) can hold NULL. Every other mapped property is NOT NULL. Label gets no column, because it has only a getter.
Exercise
Add an Author entity so that each Post has exactly one author and an author can write many posts. Which properties do you add to Author and to Post so that conventions find the relationship?
Show answer
Give Author a key and a collection: public int AuthorId { get; set; }, public string Name { get; set; } = "";, and public List<Post> Posts { get; } = new();. To Post, add a foreign key and a navigation: public int AuthorId { get; set; } and public Author Author { get; set; } = null!;. EF Core sees that the name AuthorId joins the navigation name and the key name of Author, so it treats AuthorId as the foreign key.