cezarypiatek / MappingGenerator

:arrows_counterclockwise: "AutoMapper" like, Roslyn based, code fix provider that allows to generate mapping code in design time.
https://marketplace.visualstudio.com/items?itemName=54748ff9-45fc-43c2-8ec5-cf7912bc3b84.mappinggenerator
MIT License
1.03k stars 120 forks source link

Feature request: support inheritance hierarchy flattening #113

Closed otryshko closed 4 years ago

otryshko commented 4 years ago

Hi, In my runtime object-to-storage Dto convertion I need to represent my class hierarchy with a "Type" property, i.e.

public class StorageDto{
  public string Type {get;set;}
  public sting Shared {get;set;}
  public string PropA {get;set;}
  public string PropB {get;set;}
}
public class RuntimeDtoBase{
  public sting Shared {get;set;}
}
public class RuntimeDtoA : RuntimeDtoBase{
  public string PropA {get;set;}
}
public class RuntimeDtoB : RuntimeDtoBase{
  public string PropB {get;set;}
}

Can I make the Mapping Generator to generate (for RuntimeDto -> StorageDto codepath)

var target = new StorageDto(); target.Type = typeof(source.Type)

and (for StorageDto -> RuntimeDto codepath)


if (source.Type == typeof(RuntimeDtoA)
{
  target = new RuntimeDtoA();
  ...
}
else if (source.Type == typeof(RuntimeDtoB)
{
  target = new RuntimeDtoB();
  ...
}
cezarypiatek commented 4 years ago

Hi,

It looks like a very custom logic. If you have multiple mapping pairs: (RuntimeDtoA, StorageDto), (RuntimeDtoB, StorageDto) then you should prepare an empty method for each pair and then use MappingGenerator to generate them. A method responsible for deciding which specific mapping method to invoked should be implemented manually - if you are using OnBuildGenerator then this method should be put in partial class.