Auto mapping it a helpful utility in ServiceStack that allows you to easy populate different classes with the same structure allowing you to keep appropriate separations whilst reducing lines of code.
For example, it's common in ServiceStack to keep your request and response DTO classes separate from others like your OrmLite model classes or other logic classes even thought they might share the same structure.
public class GetPersonResponse
{
public string FirstName { get;set; }
public string LastName { get;set; }
public int Age { get;set; }
}
public class Person
{
public string FirstName { get;set; }
public string LastName { get;set; }
public int Age { get;set; }
}
var person = new Person {
FirstName = "Bob",
LastName = "Smith",
Age = 40
};
var personResponse = person.ConvertTo<GetPersonResponse>();
The above example shows that we can return the same structure as a person whilst keeping it separated from the internal classes like Person
.
Other extension methods are also provided to populate your DTOs. PopulateWith
for example will add any values present on Person and populate GetPersonResponse
.
PopulateWith
will also override any values already present.
public class GetPersonResponse
{
public string FirstName { get;set; }
public string LastName { get;set; }
public int Age { get;set; }
public string PostCode { get;set; }
}
var personResponse = new GetPersonResponse() { PostCode = "3000" }.PopulateWith(person);