Explicit model mapping for Entity Framework

Introducing the EntityTypeConfiguration class

Explicit model mapping for Entity Framework
Photo by Kevin Ku on Unsplash

Let’s get stuck in!

Usually I’d go through the whole “what is x”, but I feel like that requires an article dedicated to that all by itself. So on that note, let me introduce you to one of the most interesting things I’ve found when using Entity Framework.

The source code is available on Github

Creating a simple console application

In order to show you how Entity Framework works I’ll be creating a simple console application that can read data out of an existing database. This will demonstrate that you can map tables and column names without having to use attributes on your models.

How you’ve probably seen table to model mappings 🔍

You will often see mappings done using attributes. Here is an example:

Now this is a nice and easy way to create your mappings between your models and your tables. But for more complex models I predict that your model classes may start to look a little bit messy…more [attributes] than actual code 😅

I am a bit of a stickler for SOLID principles… 🙊

I am looking specifically at the S. This stands for the Single Responsibility Principle (SRP). When using attributes on your model you are not only defining the classes that you want to use in your code, but you are also setting up your database mappings.

That sounds like TWO things 🤔

And I am sure that developers have experienced going in to their models namespace and finding some classes with attributes…and then some without 🙈

Oh…hello there EntityTypeConfiguration<T> 😙

So how do we separate the table mappings from the model? There is quite a useful class in Entity Framework that allows us to create a mapping using a separate class. This class must inherit from EntityTypeConfiguration<T>, where T is the type you want to map.

So we can take the mappings off our classes and create our type configurations like so:

When you have created your mappings, they can be added to your DbContext with one simple line 😉

Whoa…now we are SOLID! 🎉

Congratulations! Now we don’t have our table mappings mixed in with our POCOs 🙌

If you are ever working with legacy databases…then this is really REALLY useful!

Now we can access our data like we usually would with our DbContext: