Conversion from a data object to a business object. Best practice

Let's say that there is a UserEntity in the DataLayer that needs to be converted to a user in BusinessLayer. There is no 1: 1 mapping between the two types, and inheritance is not an option.

I want to convert the user to UserEntity and vice versa. What is the best way to do this? I see several patterns, but I don’t know which is better and why:

  • Implementation in User 2 methods: from Entity and ToEntity
  • Implementing TypeConverter
  • Operator Overload =
+4
source share
1 answer

Do not overload the assignment operator - it is nasty and will bite any developer who inherits your code. Better to be explicit.

I would encapsulate the logic for comparing these two types (or more, if it is not 1: 1) in a separate class. Create a UserAdapter class where you can implement ToEntity / FromEntity .

And make sure you use AutoMapper to minimize the amount of code.

AutoMapper uses the free API configuration to determine the mapping of objects to objects strategy. AutoMapper uses a matching algorithm based on map source to target values. AutoMapper is currently tuned to model projection scenarios to smooth complex object models into DTOs and other simple objects, the design of which is better suited for serialization, communication, messaging, or simply the level of corruption between the domain and the application.

Update:

You can add these methods to the User class, and this may be enough for a small project. I'm a little purist when it comes to design and will support adapter logic outside of these classes. Why should the User class be dependent and have some knowledge of the UserEntity class? It smells a bit to me to tie them together. Separate level adapters are more reliable for the future. For example, if you need to replace your database level with another (that is, switch from Linq2SQL to EntityFramework or Dapper), all you need to do is create new adapters - your business classes will remain untouched.

+2
source

All Articles