Entity Framework Database First Generalising Timestamps

Evgeny Zborovsky · August 22, 2017

Using Entity Framework is extremely easy and straight forward unless you have a large amount of entities and business rules to apply. You are lucky if you have a code first approach, however some times database first approach is in place and there are some limitations. For example, as the DbContext is autogenerated using T4, it is hard to introduce general behaviours, like updating CreatedAt, UpdatedAt and DeletedAt properties globally upon saving.

There could be different solutions for the problem I mentioned earlier, however there is a simple one that may work as well. Since all auto-generated files by EntityFramework marked as partial, we could easily extend them. Lets start!

First of all we need to make all autogenerated entities to extend an interface with our 3 properties: CreatedAt, UpdatedAt & DeletedAt. After that we have to extend our DbContext and override the SaveChangesAsync method, so it will fill the properties according to user actions. Here is the source:

Advantages:

  • Global rule, applied to all the entities in the system.
  • Logic in one place.

Disadvantages:

  • All the entities has to be manually defined in partial class and extend IEntity. Can be a pain if you have a lot of entities.
  • Can be tricky to maintain. As the system grows, it will be easy to forget the first step in this list.

This approach is not perfect but might be useful in some cases. The point of this post was to remind you that partial classes can be a very powerful tool and that you could apply code first recipes even with db first approach.

Twitter, Facebook