Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper Data Filling

Would it be possible to use AutoMapper in order to fill in an object with details from another object? For example (assuming previous configuration):

var foo = new Foo { PropA = "", PropB = "Foo" };
var bar = new Bar { PropA = "Bar", PropB = "" };

Mapper.Map<Foo, Bar>(foo, bar);

Console.WriteLine(bar.PropB); //Returns "Foo"

Just wondering if anyone has attempted this admittedly odd usage of mapping, which would be more like merging one object's matching data into another object.

Thanks in advance!

Update:

It looks like ValueInjector is a more appropriate too for this situation. There are some great discussions on appropriate uses for AutoMapper vs. ValueInjecter already on StackOverflow.

like image 755
jdscolam Avatar asked Jul 14 '26 04:07

jdscolam


2 Answers

If the property names match, then they will automatically map. If for some reason they don't you can specify the mapping yourself.

So below, PropA doesn't match PropertyA so you will have to specify the mapping. However, PropB matches, so you don't.

var foo = new Foo { PropA = "", PropB = "Foo" };
var bar = new Bar { PropertyA = "Bar", PropertyB = "" };

Mapper.CreateMap<Foo, Bar>()
      .ForMember(dest => dest.PropertyA, opt => opt.MapFrom(src => src.PropA));

Mapper.Map<Foo, Bar>(foo, bar);
like image 193
drneel Avatar answered Jul 20 '26 06:07

drneel


well, with the ValueInjecter you can do

bar.InjectFrom(foo);

and your bar will be:

{PropA = "", ProbB = "Foo"}, 

exactly the way Foo was but if you would like to take only the non null/empty values to get this

{PropA = "Foo", PropbB = "Bar"}

you can create a new Injection

public class NonNullEmptyInj : ConventionInjection
{
      protected override bool Match(ConventionInfo c)
      {
        if (c.SourceProp.Name != c.TargetProp.Name
                           || c.SourceProp.Type != c.TargetProp.Type) return false;
        if(c.SourceProp.Value == null) return false;
        if (c.SourceProp.Type == typeof(string) && c.SourceProp.Value.ToString() == string.Empty) return false;
        return true;
       }
}

and use it like this:

bar.InjectFrom<NonNullEmptyInj>(foo);
like image 43
Omu Avatar answered Jul 20 '26 06:07

Omu