Reputation: 1820
I have an object, let's call it Parent which has collections of Sons and Daughters.
public class Parent {
ICollection<Son> ParentsSons { get; set; }
ICollection<Daughter> ParentsDaughters { get; set; }
}
public class Son {
public Parent Parent { get; set; }
}
public class Daughter{
public Parent Parent { get; set; }
}
Lets assume that there are Model classes and Data classes that are being mapped back and forth.
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Data.Parent, Models.Parent>() .AfterMap((src, dest) =>
{
foreach (var i in dest.Sons)
i.Son = dest;
foreach (var i in dest.Daughters)
i.Daughters = dest;
})
.ReverseMap();
cfg.CreateMap<Data.Son, Models.Son>().ForMember(m => m.Parent, opt => opt.Ignore()).ReverseMap();
cfg.CreateMap<Data.Daughter, Models.Daughter>().ForMember(m => m.Parent, opt => opt.Ignore()).ReverseMap();
}
I am ignoring the Parent on each Son and Daughter and then mapping the Parent to each Son and Daughter in the Parent's AfterMap. This is how it was done in an example that I was following to set it up.
I can pull a parent and the collections of Sons and Daughters comes back with it and I can use them and all that and that's what I want. I can pull a Son or Daughter and the Parent comes back.
What I'm having an issue doing is pulling something back and then sending it back to save it. When I create a NEW Parent and then add Sons or Daughters to it, I can save that new Parent and it saves the Sons and Daughters and everything, but when I pull back a Parent, Son, or Daughter from the database and change something and try to send it back, it fails with a Stack Overflow exception at the mapping of Models.Parent => Data.Parent.
When I pull the data is does fine mapping Data.Parent => Models.Parent... so why the failure?
The data classes are EF generated the model classes are just copies of the data classes placed in a different layer.
Upvotes: 1
Views: 660
Reputation: 205839
You need to configure the Parent
members in reverse maps (Models -> Data) the same way as you did for Data -> Models maps:
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Data.Parent, Models.Parent>().AfterMap((src, dest) =>
{
foreach (var i in dest.Sons)
i.Parent = dest;
foreach (var i in dest.Daughters)
i.Parent = dest;
})
.ReverseMap().AfterMap((src, dest) =>
{
foreach (var i in dest.Sons)
i.Parent = dest;
foreach (var i in dest.Daughters)
i.Parent = dest;
});
cfg.CreateMap<Data.Son, Models.Son>()
.ForMember(m => m.Parent, opt => opt.Ignore())
.ReverseMap()
.ForMember(m => m.Parent, opt => opt.Ignore());
cfg.CreateMap<Data.Daughter, Models.Daughter>()
.ForMember(m => m.Parent, opt => opt.Ignore())
.ReverseMap()
.ForMember(m => m.Parent, opt => opt.Ignore());
});
Upvotes: 1