A sample mapper using source generator for .NET
https://www.nuget.org/packages/MapperGenerator/
<PackageReference Include="MapperGenerator" Version="0.0.2" />
PersonEntity.cs
public class PersonEntity
{
public int Id { get; set; }
public string Name { get; set; }
}
PersonViewModel.cs
public class PersonViewModel
{
public int Id { get; set; }
public string Name { get; set; }
}
For now we only support fully matched mapping, you need to define same type and naming of properties between two related classes.
PersonViewModel.cs
[Mapping(typeof(PersonEntity))]
public class PersonViewModel
{
public int Id { get; set; }
public string Name { get; set; }
}
Mapper.cs
//<auto-generated>
using System;
namespace MapperGenerator
{
public static class Mapper
{
public static MyConsumedApp.Models.PersonViewModel MapToPersonViewModel(MyConsumedApp.Entities.Person source)
{
var target = new MyConsumedApp.Models.PersonViewModel();
target.Id = source.Id;
target.Name = source.Name;
return target;
}
public static MyConsumedApp.Models.PersonViewModel ToPersonViewModel(this MyConsumedApp.Entities.Person source)
{
var target = new MyConsumedApp.Models.PersonViewModel();
target.Id = source.Id;
target.Name = source.Name;
return target;
}
}
}
var personEntity = new Person
{
Id = 1,
Name = "Roberson"
};
//static mapping method.
var vm1 = Mapper.MapToPersonViewModel(personEntity);
//extension method.
var vm2 = personEntity.ToPersonViewModel();
Currently it's just a prototype mapper sample created by source generator, welcome to contribute or giving any sugesstion.