1

How to ignore missing properties in destination? Now my code is

 public class UISource
{
    public string Field1  { get; set; }
    public string Field2 { get; set; }
}
public class DBTarget
{
    public string Field1 { get; set; }
    public string Field2 { get; set; }
    public string Field3 { get; set; }
    public string Field4 { get; set; }
}       
public static class Helper 
{
    public static D Map<S, D>(S uiSource) where D : class, new()
    {
        MapperConfiguration config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<S, D>();
        });
        IMapper mapper = config.CreateMapper();
        D destination = mapper.Map<S, D>(uiSource);
        return destination;
    }
}
    private void SomeMethod()
    {
        UISource uiSource = new UISource();
        uiSource.Field1 = "NewValue1";
        uiSource.Field2 = "NewValue2";

        DBTarget dbTarget = new DBTarget();
        dbTarget.Field1 = "OldValue1";
        dbTarget.Field2 = "OldValue2";
        dbTarget.Field3 = "SomeOtherValue";
        dbTarget.Field4 = "SomeOtherValue";

        dbTarget = Helper.Map<UISource, DBTarget>(uiSource);
    }

This code makes dbTarget.Field3 and dbTarget.Field4 null. I am using Automapper 4.2.1. I have tried This but its not working in latest version...

Community
  • 1
  • 1
Avinash
  • 107
  • 1
  • 1
  • 7
  • Does this answer your question? [AutoMapper: "Ignore the rest"?](https://stackoverflow.com/questions/954480/automapper-ignore-the-rest) – momvart Jun 09 '22 at 11:09

1 Answers1

0

The Map method is overloaded so you can supply a destination as well as a source. Refactor the helper class to accept D destination like this:

 public static D Map<S, D>(S uiSource, D dbTarget) where D : class, new()
    {
        MapperConfiguration config = new MapperConfiguration(
            cfg =>
                { cfg.CreateMap<S, D>(); });

        IMapper mapper = config.CreateMapper();

        D destination = mapper.Map<S, D>(uiSource, dbTarget);

        return destination;
    }

You can then call the helper like this:

dbTarget = Helper.Map<UISource, DBTarget>(uiSource, dbTarget);

Field3 and Field4 values are persisted after the mapping!

abrown
  • 715
  • 6
  • 17