AutoMapper / AutoMapper.Collection

AutoMapper support for updating existing collections by equivalency
MIT License
245 stars 59 forks source link

Not creating new child objects for collection #133

Closed JFercan closed 5 years ago

JFercan commented 5 years ago

I have the following classes and view models:

MapUser
{
    public int Id {get;set;}
    public string Name {get;set;}
    public List<MapUserGroup> UserGroups {get;set;}
}

MapGroup
{
    public int Id {get;set;}
    public string Name {get;set;}
    public List<MapUserGroup> UserGroups {get;set;}
}

MapLocation
{
    public int Id {get;set;}
    public string Name {get;set;}
}

MapUserGroup
{
    public int Id {get;set;}
    public int MapUserId {get;set;}
    public MapUser MapUser {get;set;}
    public int MapGroupId {get;set}
    public MapGroup MapGroup {get;set;}
    public int MapLocationId {get;set;}
    public MapLocation MapLocation;
}

MapUserViewModel
{
    public int Id {get;set;}
    public List<EditMapGroupViewModel> EditMapGroupViewModels;
}

EditMapGroupViewModel
{
    public int Id {get;set;}
    public int MapLocationId {get;set;}
    public int MapUserId {get;set;}
}

CreateMap<MapUserViewModel, MapUser>()
    .ForMember(d => d.UserGroups, o => o.MapFrom(s => s.EditMapGroupViewModels))

CreateMap<EditMapGroupViewModel, MapUserGroup>()
                .EqualityComparison((s, d) => s.Id == d.MapgGroupId
                    && s.MapLocationId == d.MapLocationId
                    && s.MapUserId == d.MapUserId)
                .ForMember(d => d.MapGroupId, o => o.MapFrom(s => s.Id))
                .ForMember(d => d.Id, o => o.Ignore());

The AutoMapper configurations work fine when creating a new entity of ClassA from the view model with the collection. However if I'm editing ClassA and say I add a new ClassEViewModel to the collection in ClassAViewModel, it does not map to a new entry of the ClassD collection of ClassA. Does this does not work because the comparison is done on multiple properties? If so, any ideas as to how I can accomplish this with Automapper?

PS: I do have Automapper collections installed and configured.

Thank you,

TylerCarlson1 commented 5 years ago

I'm not sure it's hard to follow. It might have to do with being fields and not properties it's not mapping over. The fact that it has multiple properties for comparison should have nothing to do with the mapping.

JFercan commented 5 years ago

@TylerCarlson1 I have updated the code to reflect better what I'm trying to do. I know it should map but unfortunately it does not work. It seems to find the existing ones but it does not create any new objects.

JFercan commented 5 years ago

Not an issue, someone added the parent mapping on a different part of the code without the child, making it have this behaviour.