Separation between Data Transfer Objects and Entities, and Automapper to the rescue

One question we had a little while ago. When you return objects from a controller, should they be the same objects you get out of your data layer?

That is, if your data layer has an object like this;

public class Project
public int ProjectId { get; set; }
public string Name { get; set; }

Should you return this direct from Controllers, like so;

public class ProjectController: ApiController
public Project Get(int id)
return this.db.GetProject(id);

And the answer Christian Weyer gave in his talk was no — use a Data Transfer Object instead. This is a pattern which has you translate from the database entity down into a very plain object designed exclusively for transferring across the wire. We’d started doing this and named them transmission objects — we would have a DB.Project class designed for inside the system, and a TX.Project class designed for transmitting over the wire, converting to JSON, etc. We had agonised a bit over the added complexity, but it’s good to see that it’s a recognised good pattern, and I’ll sleep better tonight knowing we’re doing the same as the thought-leaders.

Where his solution was much tighter than ours is that he’d used Automapper — a library which allows for very straightforward mappings between comparable types. So if DB.Project and TX.Project share similarly-named members, you end up being able to translate one to the other using calls like;

DB.Project dbProject = ...;
TX.Project txProject = dbProject.Map(); // auto-mapper kicks in here

As an adjunct to that — there is also a JsonValue class which is designed for converting to JSON. Might be worth investigating in more detail…

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s