Click here to Skip to main content
15,881,139 members
Articles / Programming Languages / C# 3.5

TinyMapper: Yet Another Object to Object Mapper for .NET

Rate me:
Please Sign up or sign in to vote.
4.92/5 (28 votes)
15 Mar 2015MIT2 min read 59.5K   316   46   17
TinyMapper is a quick object-object mapper for .NET

Introduction

TinyMapper is an object to object mapper for .NET. The main advantage is performance. TinyMapper allows easily map object to object, i.e. properties or fields from one object to another, for instance.

C#
private static void MapPerson()
{
    TinyMapper.Bind<Person, PersonDto>();

    var person = new Person
    {
        Id = Guid.NewGuid(),
        FirstName = "John",
        LastName = "Doe",
        Email = "support@tinymapper.net",
        Address = "Wall Street",
        CreateTime = DateTime.Now,
        Nickname = "Object Mapper",
        Phone = "Call Me Maybe "
    };

    var personDto = TinyMapper.Map<PersonDto>(person);
}

Performance

Yes, this chapter has to be on the end. I believe most of you know what object mappers are, so let's talk about performance briefly.

We'll use the same Person class for the testing purpose.

C#
public sealed class Person
{
    public string Address { get; set; }
    public string Email { get; set; }
    public string FirstName { get; set; }
    public Guid Id { get; set; }
    public string LastName { get; set; }
    public string Nickname { get; set; }
    public DateTime CreateTime { get; set; }
    public string Phone { get; set; }
}

PersonDto class is the same as the Person. We'll compare:

During the test, we create a Person class instance and map all properties on the PersonDto class.

C#
private static void MeasureHandwritten()
{
    Person person = CreatePerson();

    Stopwatch stopwatch = Stopwatch.StartNew();

    for (int i = 0; i < Iterations; i++)
    {
        PersonDto personDto = MapHandwritten(person);
    }
    stopwatch.Stop();
    Console.WriteLine("Handwritten: {0}ms", stopwatch.Elapsed.TotalMilliseconds);
}

private static void MeasureTinyMapper()
{
    Person person = CreatePerson();
    TinyMapper.Bind<Person, PersonDto>();

    Stopwatch stopwatch = Stopwatch.StartNew();

    for (int i = 0; i < Iterations; i++)
    {
        var personDto = TinyMapper.Map<PersonDto>(person);
    }

    stopwatch.Stop();
    Console.WriteLine("TinyMapper: {0}ms", stopwatch.Elapsed.TotalMilliseconds);
}

private static void MeasureAutoMapper()
{
    Person person = CreatePerson();
    Mapper.CreateMap<Person, PersonDto>();

    Stopwatch stopwatch = Stopwatch.StartNew();

    for (int i = 0; i < Iterations; i++)
    {
        var personDto = Mapper.Map<PersonDto>(person);
    }
    stopwatch.Stop();
    Console.WriteLine("AutoMapper: {0}ms", stopwatch.Elapsed.TotalMilliseconds);
}

where CreatePerson

C#
private static Person CreatePerson()
{
    return new Person
    {
        Id = Guid.NewGuid(),
        FirstName = "John",
        LastName = "Doe",
        Email = "support@tinymapper.net",
        Address = "Wall Street",
        CreateTime = DateTime.Now,
        Nickname = "Object Mapper",
        Phone = "Call Me Maybe "
    };
}

and MapHandwritten

private static PersonDto MapHandwritten(Person person)
{
    var result = new PersonDto
    {
        Id = person.Id,
        FirstName = person.FirstName,
        LastName = person.LastName,
        Email = person.Email,
        Address = person.Address,
        CreateTime = person.CreateTime,
        Nickname = person.Nickname,
        Phone = person.Phone
    };
    return result;
}

we repeat measurement 1 000 000 times.

Image 1  

Getting Started

TinyMapper is available thru nugen, so you can install as all NuGet package. for example through Package Manager Console.

Image 2

Okay, we're ready to start. First of all, you've to Bind source type to target type, like this.

C#
TinyMapper.Bind<Person, PersonDto>();

Now TinyMapper knows how to map Person object to PersonDto object. Finally, call

C#
var personDto = TinyMapper.Map<PersonDto>(person);

and you'll get mapped object. Here's the full version.

Image 3

So you have to do two steps:

  • Bind source type to the target type
  • Map source object to the target type
Quote:

Note: if you're multithreading an application, register all bindings on application start. While the application is running, you'll call only Map method. So, you'll get speed and thread safe.

TinyMapper can do the first step for you, i.e., you can just call Map and the result will be the same.

Image 4

Quote:

Note: Be careful to call Map without Bind, it's not thread safe.

More Complex Example

Let's take a look at a more complex sample. For example, we have the following classes.

C#
public sealed class PersonComplex
{
    public Address Address { get; set; }
    public DateTime CreateTime { get; set; }
    public IReadOnlyList<string> Emails { get; set; }
    public string FirstName { get; set; }
    public Guid Id { get; set; }
    public string LastName { get; set; }
    public string Nickname { get; set; }
}

public sealed class Address
{
    public string Phone { get; set; }
    public string Street { get; set; }
    public string ZipCode { get; set; }
}

and we don't want to map CreateTime and Nickname properties.

Image 5

As you can see, we've just marked CreateTime and Nickname as ignored. Bind LastName from the source Surname to the target class and bind IList of emails to List

TinyMapper allows:

  • Ignore fields
  • Map one field to a different field
  • Map interface to exact type

Custom Mapping

For instance, we have the following classes:

C#
public sealed class PersonCustomSource
{
    public IList<string> Emails { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public sealed class PersonCustomTarget
{
    public IList<string> Emails { get; set; }
    public string FullName { get; set; }
}

We want to map:

  • FirsName and LastName to FullName with the following convention "FirstName LastName"

TinyMapper supports TypeConverter, i.e., you can create your own TypeConverter for any type.

C#
public sealed class PersonTypeConverter : TypeConverter
{
    public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
    {
        return destinationType == typeof(PersonCustomTarget);
    }

    public override object ConvertTo
    (ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
    {
        var concreteValue = (PersonCustomSource)value;
        var result = new PersonCustomTarget
        {
            FullName = string.Format("{0} {1}", concreteValue.FirstName, concreteValue.LastName),
            Emails = new List<string>(concreteValue.Emails)
        };
        return result;
    }
}

The next step is to register the type converter. TypeConverter supports registration through attribute...

C#
[TypeConverter(typeof(PersonTypeConverter))]
public sealed class PersonCustomSource
{
    public IList<string> Emails { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

...or code

C#
TypeDescriptor.AddAttributes(typeof(PersonCustomSource), 
	new TypeConverterAttribute(typeof(PersonTypeConverter)));

Image 6

Here's an additional sample of how to implement a type converter.

Under the Hood

It's a long story. In the next article, I'll describe in detail about how TinyMapper works. Internally, TinyMapper generates mapping code through ILGenerator. The mapping code looks almost the same as handwritten code. For instance, the following code was generated for Person to PersonDto mapping.

Image 7

I hope you enjoyed it. Thanks for reading the article.

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Software Developer (Senior)
United States United States
B.Sc. in Computer Science.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Sandeep Mewara12-Jul-20 21:36
mveSandeep Mewara12-Jul-20 21:36 
Questioncan it be used with entity framework Pin
ovisariesdk13-Oct-17 6:53
ovisariesdk13-Oct-17 6:53 
AnswerRe: can it be used with entity framework Pin
Sergey Morenko26-Oct-17 10:32
professionalSergey Morenko26-Oct-17 10:32 
QuestionHow much faster than a dictionary and tuple? Pin
tugrulGtx20-Apr-17 2:02
tugrulGtx20-Apr-17 2:02 
AnswerRe: How much faster than a dictionary and tuple? Pin
Sergey Morenko20-Apr-17 10:20
professionalSergey Morenko20-Apr-17 10:20 
GeneralRe: How much faster than a dictionary and tuple? Pin
tugrulGtx20-Apr-17 10:53
tugrulGtx20-Apr-17 10:53 
SuggestionBut How? Pin
John B Oliver26-Mar-15 11:18
John B Oliver26-Mar-15 11:18 
GeneralRe: But How? Pin
Sergey Morenko26-Mar-15 21:14
professionalSergey Morenko26-Mar-15 21:14 
GeneralRe: But How? Pin
Ehsan Sajjad15-Mar-17 0:30
professionalEhsan Sajjad15-Mar-17 0:30 
QuestionThank you! Pin
Shabbazz19-Mar-15 17:13
professionalShabbazz19-Mar-15 17:13 
AnswerRe: Thank you! Pin
Sergey Morenko19-Mar-15 20:26
professionalSergey Morenko19-Mar-15 20:26 
QuestionThread Safety Pin
Denis Ibragimov16-Mar-15 12:51
professionalDenis Ibragimov16-Mar-15 12:51 
AnswerRe: Thread Safety Pin
Sergey Morenko16-Mar-15 23:29
professionalSergey Morenko16-Mar-15 23:29 
GeneralVery Nice Pin
Muhammad Essa Rind15-Mar-15 9:27
Muhammad Essa Rind15-Mar-15 9:27 
GeneralRe: Very Nice Pin
Sergey Morenko15-Mar-15 11:18
professionalSergey Morenko15-Mar-15 11:18 
Generalvery nice Pin
joyhen12312315-Mar-15 7:54
joyhen12312315-Mar-15 7:54 
GeneralRe: very nice Pin
Sergey Morenko15-Mar-15 11:18
professionalSergey Morenko15-Mar-15 11:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.