2020-12-21 19:34:53 +03:00
# MapTo
2020-12-24 15:42:28 +03:00
![Nuget ](https://img.shields.io/nuget/v/mapto?logo=nuget )
![Publish Packages ](https://github.com/mrtaikandi/MapTo/workflows/Publish%20Packages/badge.svg )
2020-12-27 10:34:27 +03:00
A convention based object to object mapper using [Roslyn source generator ](https://github.com/dotnet/roslyn/blob/master/docs/features/source-generators.md ).
2020-12-24 23:28:34 +03:00
2020-12-27 10:34:27 +03:00
MapTo creates mappings during compile-time, which eliminates the need for using reflection to create the mappings. This makes it super simple to use and way faster than other libraries.
2020-12-22 11:20:49 +03:00
## Installation
```
2020-12-24 15:42:28 +03:00
dotnet add package MapTo --prerelease
2020-12-22 11:20:49 +03:00
```
## Usage
2020-12-24 23:28:34 +03:00
To generate the mappings, simply declare the destination class as `partial` and annotate it with `MapFrom` attribute.
2020-12-22 11:20:49 +03:00
```c#
2020-12-24 23:28:34 +03:00
using MapTo;
2020-12-22 11:20:49 +03:00
2020-12-24 23:28:34 +03:00
namespace App.ViewModels
{
[MapFrom(typeof(App.Data.Models.User))]
public partial class UserViewModel
{
public string FirstName { get; }
2020-12-24 15:45:31 +03:00
2020-12-24 23:28:34 +03:00
public string LastName { get; }
[IgnoreProperty]
public string FullName { get; set; }
}
2020-12-22 11:20:49 +03:00
}
```
2020-12-24 23:28:34 +03:00
## Generated Source
In the above example, if `App.Data.Models.User` class is defined as:
2020-12-22 11:20:49 +03:00
```c#
namespace App.Data.Models
{
public class User
{
public User(int id) => Id = id;
public int Id { get; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName => $"{FirstName} {LastName}";
}
}
```
It will generate the following code:
```c#
// < auto-generated / >
using System;
namespace App.ViewModels
{
public partial class UserViewModel
{
public UserViewModel(App.Data.Models.User user)
{
if (user == null) throw new ArgumentNullException(nameof(user));
2020-12-22 11:28:14 +03:00
2020-12-22 11:20:49 +03:00
FirstName = user.FirstName;
LastName = user.LastName;
}
public static UserViewModel From(App.Data.Models.User user)
{
return user == null ? null : new UserViewModel(user);
}
}
2020-12-22 11:28:14 +03:00
public static partial class UserToUserViewModelExtensions
2020-12-22 11:20:49 +03:00
{
public static UserViewModel ToUserViewModel(this App.Data.Models.User user)
{
return user == null ? null : new UserViewModel(user);
}
}
}
```
Which makes it possible to get an instance of `UserViewModel` from one of the following ways:
```c#
var user = new User(id: 10) { FirstName = "John", LastName = "Doe" };
var vm = user.ToUserViewModel();
// OR
vm = new UserViewModel(user);
// OR
vm = UserViewModel.From(user);
```