.NET Naming Best Practises: Database Entities

.NET Naming Best Practises: Database Entities

Database entities are the objects that represent the tables in your database. They are the objects that you use to read and write the database.

Naming

Naming database entities and their respective classes is a little more complicated than the other object types we have looked at so far.
But it is actually only more complex because there are ORMs such as Dapper and EF Core, whose code examples often do not correspond to best practices and suggest things that are not the case in reality and real-world applications.

Entities are not business models

Entities are often referred to as business models in various documentations - but they are not. Even in the Ent ity Framework documentation, this was the case for a long time, which is why there were repeated misunderstandings, both in terms of naming and implementation.

Entities are the objects that represent the database. They are the objects that you use to read and write the database. However, they are not business models and should not be used for this purpose. In modern, up-to-date documentation, they are no longer referred to as business models, but as complex data models.
The difference between an entity and a business model is that entities only represent the data structure and only hold the associated data; there is no business implementation, neither in the entity itself nor together with the entity. Entities are purely optimized and structured for data storage.

In some modern software architectures, business models are even completely dispensed with as class implementations; they only exist virtually in the design of the software architecture.

Correct Naming

Like all other things, entities should be named so that it is immediately recognizable what they are: Entities.

An entity for a user is therefore a UserEntity and not simply User.

// wrong
public class User ...
public class UserDto ...
public class UserModel ...
public class UserData ...

// correct
public class UserEntity ...

Projections

Closely linked to entities are projections; while the entity is the full image of the database table, the projection is the result of a query that contains only the data that is required.\ This data can come from a table, as well as selections from other tables or even completely new data that is composed of several tables or database-side operations.

// correct
public class UserOrderInformationProjection
{
    // From UserEntity
    public int      Id { get; set; }
    public string   Name { get; set; }

    // From UserContactEntity
    public string Email { get; set; }
    public string Address { get; set; }

    // Calculated
    public DateTimeOffset? LastOrderOn { get; set; }
    public int TotalOrders { get; set; }
}

PS: while entities cannot be implemented as records, projections could.