Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
latonz opened this issue May 28, 2024 · 1 comment
Open

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

latonz opened this issue May 28, 2024 · 1 comment
Labels
enhancement New feature or request

Comments

@latonz
Copy link
Contributor

latonz commented May 28, 2024

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:

  • What type conversions should be supported? => For now only casting.
  • What happens with required but unmapped members? => throw an exception
  • What happens if a value is provided for a member but it cannot be converted to the target type? => throw an exception
  • How to map nested objects?

Example

Definition
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<string, object?> source);
}
Generated code
public partial class MyMapper
{
    public partial Apple Map(IReadOnlyDictionary<string, object?> 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. #1041 and #1039

@latonz latonz added the enhancement New feature or request label May 28, 2024
@leoerlandsson
Copy link

leoerlandsson commented May 28, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants