C# Entity – Should an Entity Object Be Extended with a Separate Class?

centity

I have a simple entity class in my C# application that I would like to add additional properties to for use in the app. These properties will not be persisted to the database.

In the past, I was told that the entity should mirror the object as it appears in the database, and that a separate class file should be used that inherits from the original entity class for additional properties and business logic.

Is this necessary?

Best Answer

The concept of two classes, one that mirrors the database and the other that adds additional properties and business logic, is influenced/inspired by Entity Framework. It is a direct consequence of the code generation process that Entity Framework uses to create "mirror" database objects, in "database-first" mode. It's not implemented using inheritance, but by using partial classes; one partial mirrors the database, the other adds the business logic. It is done that way so that your business logic is not overwritten if you run the code generator again.

The concept of sub-classing an existing class to add additional functionality is not new; it's simple inheritance, fundamental to object-oriented principles. And yes, it does make sense. Whether it's necessary or not depends on your specific project's requirements.