9

Separation between Data Transfer Objects and Entities, and Automapper to the res...

 3 years ago
source link: https://stevedrivendevelopment.com/2013/03/06/separation-between-data-transfer-objects-and-entities-and-automapper-to-the-rescue/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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…


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK