Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper settings properties to null on destination object

Tags:

c#

automapper

I have something like this:

public class DomainEntity
{
    public string Name { get; set; }
    public string Street { get; set; }
    public IEnumerable<DomainOtherEntity> OtherEntities { get; set; }
    public IEnumerable<DomainAnotherEntity> AnotherEntities { get; set; }
}

public class ApiEntity
{
    public string Name { get; set; }
    public string Street { get; set; }
    public int OtherEntitiesCount { get; set; }
}

And following mapper configuration:

Mapper.Configuration.AllowNullCollections = true;

Mapper.CreateMap<DomainEntity, ApiEntity>().
    ForSourceMember(e => e.OtherEntities, opt => opt.Ignore()).
    ForSourceMember(e => e.AntherEntities, opt => opt.Ignore()).
    ForMember(e => e.OtherEntitiesCount, opt => opt.MapFrom(src => src.OtherEntities.Count()));

Mapper.CreateMap<ApiEntity, DomainEntity>().
    ForSourceMember(e => e.OtherEntitiesCount, opt => opt.Ignore()).
    ForMember(e => e.OtherEntities, opt => opt.Ignore()).
    ForMember(e => e.AnotherEntities, opt => opt.Ignore());

To get the ApiEntity from the DomainEntity I'm using var apiEntity = Mapper.Map<DomainEntity, ApiEntity>(myDomainEntity);

To get the merged DomainEntity from an ApiEntity I'm using var domainEntity = Mapper.Map(myApiEntity, myDomainEntity);

But when using this, the properties OtherEntities and AnotherEntities are set to null - even when they had values before calling the mapping from myApiEntity to myDomainEntity. How can I avoid this so they really merge and not just replacing values?

Thanks for any help.

like image 218
Felix C Avatar asked Apr 20 '13 22:04

Felix C


1 Answers

I think you're looking for UseDestinationValue instead of Ignore:

Mapper.CreateMap<ApiEntity, DomainEntity>().
    ForSourceMember(e => e.OtherEntitiesCount, opt => opt.UseDestinationValue()).
    ForMember(e => e.OtherEntities, opt => opt.UseDestinationValue()).
    ForMember(e => e.AnotherEntities, opt => opt.UseDestinationValue());
like image 57
Andrew Whitaker Avatar answered Oct 30 '22 19:10

Andrew Whitaker