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?

  • 2
    Another alternative to subclassing might be to use a decorator. – Philipp Mar 29 '17 at 15:40
  • I agree, I don't think I would sub-class an entity object unless I intended to use it as a distinct entity (for instance, I've sometimes used a base entity object that only had a pkey defined, that other entities inherited from). If you only want to add business logic (make sure you don't confuse business logic and data logic), then I would suggest creating a separate domain object that you can map your entity object to and it would contain your business logic. Then the rest of your application depends on the domain object, not the entity object. Look up "Onion Architecture" for more info. – Michael L. Mar 29 '17 at 17:24

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.