Mapping from the source object
Thundarr1974 opened this issue Β· comments
When mapping to a Target field there's often a need to access multiple fields from the Source and today this requires creating a custom mapping method like so:
public Address OrderToAddress(Order order)
{
var ret = MapToAddress(order);
ret.FullName = string.Concat(order.FirstName, " ", order.LastName);
return ret;
}
[MapperIgnoreTarget(nameof(Address.FullName))]
private partial Address MapToAddress(Order order);
I propose a new [MapSource] (or some other name) attribute that supports using the Source object as the 'from' parameter like so:
[MapSource(nameof(Address.FullName))]
public partial Address OrderToAddress(Order order);
private string MapToFullName(Order order) => string.Concat(order.FirstName, " ", order.LastName);
In our opinion this is easier to implement using a before/after map approach instead of expanding the API surface of Mapperly. Also this increases the risk of business logic beeing implemented in the Mapper.
The major downside of the after map approach is it requires a [MapperIgnoreTarget] declaration if you're using strict enforcement (which we do to ensure no target fields are left out). So IMHO it negates one of Mapperly's greatest features.
This makes it unclear to other developers if the field is actually mapped or not so they have to go hunting...
Makes sense.
Regarding the naming: I think MapPropertyFromSourceAttribute
would be slightly better to align with the existing MapPropertyAttribute
.
The API could look like this:
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
[Conditional("MAPPERLY_ABSTRACTIONS_SCOPE_RUNTIME")]
public sealed class MapPropertyFromSourceAttribute : Attribute
{
public MapPropertyFromSourceAttribute(string target);
public MapPropertyFromSourceAttribute(string[] target);
public string? StringFormat { get; set; }
public string? FormatProvider { get; set; }
public string? Use { get; set; }
}
You are more than welcome to contribute π
π This issue has been resolved in version 3.6.0-next.1 π
The release is available on:
- GitHub release
v3.6.0-next.1
Your semantic-release bot π¦π
π This issue has been resolved in version 3.6.0 π
The release is available on:
- GitHub release
v3.6.0
Your semantic-release bot π¦π