riok / mapperly

A .NET source generator for generating object mappings. No runtime reflection.
https://mapperly.riok.app
Apache License 2.0
2.44k stars 130 forks source link

Support mapping from `Dictionary<string, object?>` #1309

Open latonz opened 1 month ago

latonz commented 1 month ago

Add support for mappings with a class/struct target and a source implementing IReadOnlyDictionary<string, TValue> or IDictionary<string, TValue> with TValue beeing either object or object?.

Questions to be discussed:

Example

Definition ```csharp public class Fruit { public required string Name { get; init; } public int Weight { get; set; } public Color Color { get; set; } } public enum Color { Red, Green } [Mapper] public partial class MyMapper { public partial Apple Map(IReadOnlyDictionary source); } ```
Generated code ```csharp public partial class MyMapper { public partial Apple Map(IReadOnlyDictionary source) { var target = new Apple { Name = (string)source.GetValueOrDefault(nameof(Apple.Name)) ?? throw ... }; if (source.TryGetValue(nameof(Apple.Weight), out var weight)) { target.Weight = (int)weight; } if (source.TryGetValue(nameof(Apple.Color), out var color)) { target.Color = (Color)color; } return weight; } private partial int ParseString(string source) { return int.Parse(source); } private partial Color ParseColor(string source) { return source switch { nameof(Color.Red) => Color.Red, nameof(Color.Green) => Color.Green, _ => throw ... }; } } ```

Rel. https://github.com/riok/mapperly/issues/1041 and https://github.com/riok/mapperly/discussions/1039

leoerlandsson commented 1 month ago

Interesting, I was just looking for this functionality :D

The other way around would be useful aswell, i.e mapping from an object to a Dictionary.