vendredi 19 janvier 2018

Reusing DTO objects for Display and Edit / Create

Working on a ASP.Net MVC Project where we are creating DTO objects to capture the data from our Entities for use on our Views. Let's call our DTO object EntityDto which maps to an Entity. We'll add a User class as well as part of this example.

Here are the Entity Classes:

public class User {
  public int Id;
  public string UserName;
}

public class Entity {
  public int Id;
  public string Name;
  public User AssignedTo;
}

Let's say we have 2 views for this: one is a simple listing view in a grid, and the other is a form for editing the Entity data. So, I start out with creating a DTO for the grid.

public class EntityDto {
  public string Name;  // Entity.Name
  public string AssignedTo;  // ie: User.UserName
}

I assign the Model of my view to be of type List<EntityDto>. So far, so good.

On my form to edit this Entity, I need to both display and edit the data, and the above DTO will no longer work: I will need the User.Id value to be stored somewhere.

A principle for DTO's is to keep them flat as possible, with no behaviours. Based on the above requirements, I think I have the following three options:

Option 1: Create a new EntityDto, say EntitySaveDto specific to the new View, reflecting that I now need a different field set. To me this is least desirable due to zero code re-use.

Option 2: Edit my EntityDto to add the missing fields I need. Some fields will then not be used in other contexts (like the grid view). This means I will have the following Dto:

public class EntityDto {
  public string Name;  // Entity.Name
  public int AssignedToId;  // ie: User.Id
  public string AssignedToName;  // ie: User.UserName
}

Option 3: Is it better to define a helper Dto that has an Id and Name pair. I'm finding the pattern of needing an Id and a Name repeats itself. In this scenario, the class structure would look like:

public class EntityLookupDto {
  public int Id;
  public string Name;
}

public class EntityDto {
  public string Name;
  public EntityLookupDto AssignedTo;  // where AssignedTo now has both the Id and Name for the associated User
}

From reading on this topic, it seems that most of the answers are "depends".

My gut tells me that Option 3 will offer efficiencies in other aspects of the application, such as my AutoMapper configuration, for instance. But are there drawbacks that I should be considering?

Aucun commentaire:

Enregistrer un commentaire