Friday 24 July 2015

Entities to database mapping in EntityFramework

In this post I'm going to share different ideas to map domain entities to database schema in Code First development. In all of the approaches, I'm going to derive from DbContext class and overrides its OnModelCreating method. You can still use the ideas from this post even if you're directly using DbModelBuilder to create DbContext. For the purpose of this post I'm using two classes- Product and Brand; you can find them here.
1. Difficult to scale approach- This is a kind of "hello world" approach. In this approach you can provide mapping directly inside OnModelCreating method; something like below- This approach is not suitable of enterprise applications. This can easily get messy when number of entities will grow in project.
2. Not so difficult to scale- In this approach you will define entities to database mapping by deriving from EntityTypeConfiguration and ComplexTypeConfiguration. In this case mapping of each entity is confined to one class; conforming to SRP principal. Here is how you can define mapping in entity configuration classes- Now you can add these entity/complex type configurations directly in to DbModelBuilder. Our custom DbContext looks cleaner now- This approach helps us to move good amount of code in to separate independent mapping classes however you will still have to come back to custom DbContext class to add any new entity/complex type configuration, which is not a serious problem but it can be improved.
3. Easily scalable- Entity Framework provides a method, which can scan all the entity/complex type configurations from a given assembly and add them to DbModelBuilder. You can keep all these mapping configurations in a separate dedicated assembly for better organization and help the reflector not to filter out configurations from the non-configuration types. Here is how you can write custom DbContext using this approach- In this approach new entity/complex type configurations will be added to Entity Framework model without changing the custom DbContext and it plays well with our generic repository pattern. Performance wise it was not a problem for me because OnModelCreating is called only once when starting your application.

No comments:

Post a Comment

Guflow added support for timeout in signal APIs

Just released version - 2.0.5 of Guflow has added the support for timeout in signal APIs. Now with minimum efforts you can support the human...