Skip to content

Instantly share code, notes, and snippets.

@Layoric
Last active September 1, 2016 02:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Layoric/1750411dd208e16f915919a674709296 to your computer and use it in GitHub Desktop.
Save Layoric/1750411dd208e16f915919a674709296 to your computer and use it in GitHub Desktop.
Auto mapping

Auto mapping

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>();

Live Example

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);

Live Example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment