4.4: Adding User DTOs
We need to think about shaping our data that we send back to the client. When a user requests another user or all users - we don't want to send back password hash/salt, for example.
We'll use DTOs to shape the data and choose what we return in our service.
UserForList
Inside of the User folder in your .Models project - add a new file called UserForList.cs
You can copy and edit the properties from the User.cs class - or type them in manually:
public class UserForList
{
public int Id { get; set; }
public string Username { get; set; }
public string Specialty { get; set; }
public int Age { get; set; }
public string KnownAs { get; set; }
public DateTime Created { get; set; }
public DateTime LastActive { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PhotoUrl { get; set; }
}We eliminated some properties that we do not want to return for the list of users.
We changed DateOfBirth to Age - we'll add an extension method to calculate that from their date of birth. We also added a property that doesn't exist on user called PhotoUrl. This will be their "main" photo - that we can find from their Photo collection.
UserForDetail
Next, create another class inside the User folder in your .Models project called UserForDetail.cs:
public class UserForDetail
{
public int Id { get; set; }
public string Username { get; set; }
public string Specialty { get; set; }
public int Age { get; set; }
public string KnownAs { get; set; }
public DateTime Created { get; set; }
public DateTime LastActive { get; set; }
public string Introduction { get; set; }
public string LookingFor { get; set; }
public string Interests { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PhotoUrl { get; set; }
public ICollection<PhotoForDetail> Photos { get; set; }
}We're returning a collection of PhotoForDetails instead of the Photo entities. We'll create that DTO next.
PhotoForDetail
Next, we'll create a DTO to define a Photo we'd like to return.
Create a new folder in your .Models project called Photo and add a new class to it called PhotoForDetail.cs:
public class PhotoForDetail
{
public int Id { get; set; }
public string Url { get; set; }
public string Description { get; set; }
public DateTime DateAdded { get; set; }
public bool IsMain { get; set; }
}Last updated