Go to file
Mohammadreza a46891cb2d
Update dotnet.yml
2020-12-22 16:28:05 +00:00
.github/workflows Update dotnet.yml 2020-12-22 16:28:05 +00:00
MapTo Add versioning. 2020-12-22 16:13:36 +00:00
MapToTests Cleanup. 2020-12-21 16:34:53 +00:00
TestConsoleApp Remove redundant using statement in generated code. 2020-12-22 08:28:14 +00:00
.editorconfig Cleanup. 2020-12-21 16:34:53 +00:00
.gitignore Generate partial class and assign destination properties based on an attribute. 2020-12-19 07:55:47 +00:00
Directory.Build.props Add versioning. 2020-12-22 16:13:36 +00:00
LICENSE Cleanup. 2020-12-21 16:34:53 +00:00
MapTo.sln Add test console app and fix generator not running during compile time. 2020-12-21 10:20:29 +00:00
MapTo.sln.DotSettings Generate partial class and assign destination properties based on an attribute. 2020-12-19 07:55:47 +00:00
README.md Remove redundant using statement in generated code. 2020-12-22 08:28:14 +00:00
version.json Add versioning. 2020-12-22 16:13:36 +00:00

README.md

MapTo

An object to object mapping generator using using Roslyn source generator.

Installation

dotnet add package MapTo

Usage

MapTo creates mappings during compile-time. To indicate which objects it needs to generate the mappings for, simply declare the class as partial and annotate it with MapFrom attribute.

[MapFrom(sourceType: typeof(App.Data.Models.User))]
public partial class UserViewModel 
{
    public string FirstName { get; }

    public string LastName { get; }
}

If Data.Models.User class is defined as follow:

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:

// <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));
            
            FirstName = user.FirstName;
            LastName = user.LastName;
        }

        public static UserViewModel From(App.Data.Models.User user)
        {
            return user == null ? null : new UserViewModel(user);
        }
    }

    public static partial class UserToUserViewModelExtensions
    {
        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:

var user = new User(id: 10) { FirstName = "John", LastName = "Doe" };

var vm = user.ToUserViewModel();

// OR
vm = new UserViewModel(user);

// OR
vm = UserViewModel.From(user);