Make entities inherit from a base class in Entity Framework Core DB First

It’s often useful to have our entities inherit from a base class. This is easily done using EF Core Power Tools which is a Visual Studio extension that provides a graphical rather than command line based approach to scaffolding.

EF Core Power Tools uses the Scaffolding.Handlebars library to support the customization of code which is generated during the scaffolding process. You don’t need the VS extension to use the library but it’s a bit easier and EF Core Power Tools is a great extension anyway so I’ll use it in the post.

The steps are…

Install the extension via the Extensions -> Manage Extensions window (you’ll then see the menu as a right-click option on your projects).

Right click on the relevant project and select EF Core Power Tools -> Reverse Engineer and first select which tables you want to scaffold and then on the subsequent screen check the option for customizing the code.

Reverse Engineer

After running the scaffolding you should see entities generated AND a CodeTemplates folder which contains all the handlebar template files for customizing entities and the DbContext.

To inherit from a base class just amend the Class template (Class.hbs) file as shown on the left below.

Inherit from a base class

Re-scaffold again with right click -> EF Core Power Tools -> Reverse Engineer and all your entities should now inherit from the base class

Entity inheriting base class example

Of course to have your entities implement an interface the process is identical.

Leave a Reply

Your email address will not be published. Required fields are marked *