/SourceGeneratorMapper

Simple source generator to create mapping extension methods

Primary LanguageC#MIT LicenseMIT

Simple Source Generator Mapper


This is a simple source generator to create mapping extension methods.

Overview

SourceGeneratorMapper is a source generator that automates the creation of mapping extension methods to map one type to another. This is particularly useful in scenarios where you need to convert between different data transfer objects (DTOs), view models, or any other types with similar properties.

Features

  • Automatically generates mapping extension methods to map one type to another.
  • Allows for custom property mappings using attributes.

Usage

Mapping Types

To map one type to another, use the MapTo attribute and provide the target type you want to map to.

[MapTo(typeof(TargetType))]
public class SourceType
{
    public string TargetPropertyName { get; set; }
    // Properties
}

Mapping Properties

To map specific properties, use the MapToProperty attribute and provide the target property name you want to map to.

public class SourceType
{
    [MapToProperty("TargetPropertyName")]
    public string SourcePropertyName { get; set; }
    // Properties
}

Specifying Output Directory

To specify directory where mapping will be generated, use the OutputDirectory attribute and provide the target directory name you want to generate to.

[OutputDirectory("Generated")]
public class SourceType
{
    public string SourcePropertyName { get; set; }
    // Properties
}

Example

Source Type

[MapTo(typeof(TargetType))]
public class SourceType
{
    public int Id { get; set; }
    
    [MapToProperty("FullName")]
    public string Name { get; set; }
    
    public DateTime DateOfBirth { get; set; }
}

Target Type

public class TargetType
{
    public int Id { get; set; }

    public string FullName { get; set; }

    public DateTime DateOfBirth { get; set; }
}

Generated Mapping Extension

public static class SourceTypeMappingExtension
{
    public static TargetType MapToTargetType(this SourceType from)
    {
        return new TargetType
        {
            Id = from.Id,
            FullName = from.Name,
            DateOfBirth = from.DateOfBirth
        };
    }
}