2

Say I have the following related entities with one-to-one relationships:

public class A {
    public int Id {get; set;}
    public string Name {get; set;}
    public string Address {get; set;}

    public virtual B B {get; set;}
    public virtual int BId {get; set;}
}


public class B {
    public int Id {get; set;}
    public decimal Price {get; set;}

    public virtual A A {get; set;}
    public virtual int AId {get; set;}
}

And the single class (DTO) that will contain the fields for both these classes:

public class C {
    public int Id {get; set;} //which will correspond to AId
    public string Name {get; set;}
    public string Address {get; set;}
    public decimal Price {get; set;}
}

How do I map from class C to class A and B using Automapper? When I use the following, it says that the navigation properties (B for class A, and A for class B) are null:

CreateMap<C, A>().ReverseMap();
CreateMap<C, B>()
    .ForMember(b => b.AId, opt => opt.MapFrom(c => c.Id))
    .ReverseMap();

And when I try to call a Mapper.Map function inside CreateMap it yields an error where Mapper must be initialized first. Can someone point me in the right direction on how to go about this?

Milo
  • 3,365
  • 9
  • 30
  • 44
E. Rosales
  • 21
  • 2
  • Is this what you're looking for? https://stackoverflow.com/questions/2374689/automapper-update-property-values-without-creating-a-new-object – Barry O'Kane Jun 07 '18 at 11:36
  • 1
    Create 2 mapping profiles. From A to C and from B to C. Then first let an instance of A map to C. After that map an instance of B to C but passing the instance of C that was created with the A-to-C mapping – Schadensbegrenzer Jun 07 '18 at 11:38
  • Oh, I see! Didn't think of updating the current instance already created, and I didn't know there was an overload for it. Thank you very much! – E. Rosales Jun 07 '18 at 15:53

0 Answers0