MapsterMapper / Mapster

A fast, fun and stimulating object to object Mapper
MIT License
4.38k stars 331 forks source link

New object is created on destination instead of null when using Adapt<> #693

Open nikitabraganov opened 7 months ago

nikitabraganov commented 7 months ago

I have the following classes:

ScheduleWrapper

 public Guid ID { get; set; }  
 public Guid? CompanyID { get; set; }  
 public CItyWrapper City {get;set;}  
 public CItyWrapper City1 {get;set;}  

Schedule

 public Guid ID { get; set; }
 public Guid? CompanyID { get; set; }
 public Company Company { get; set; }
 public CIty Start{get;set;}
 public CIty End {get;set;}

When I try to adapt ScheduleWrapper to Schedule, on Schedule an empty Company object will be created instead of null.

Other configurations are:

config.Default.PreserveReference(true);
config.Default.IgnoreNullValues(true);
config.NewConfig<Schedule, ScheduleWrapper>().TwoWays()
                .Map(dest => dest.City, src => src.Start)
                .Map(dest => dest.City1, src => src.End);

I noticed this behavior also in other places where the explicit mapping is not defined.

Is there a setting to not create empty objects on destination when it not exists on source?

nikitabraganov commented 7 months ago

I migrated from AutoMapper, and there I had the "AllowNullDestinationValues" property on the MapperConfiguration.

nikitabraganov commented 7 months ago

@andrerav

savornicesei commented 1 month ago

A little too late to the party but I just hit the same problem. This is how I fixed it

        config.NewConfig<ProductCategory, SaveProductCategoryDto>()
            .MaxDepth(1);
        config.NewConfig<SaveProductCategoryDto, ProductCategory>()
            .IgnoreMember((member, side) => side == MemberSide.Destination
                                            && member.Name.Equals(nameof(ProductCategory.Company)))
            .IgnoreNullValues(true)
            .MaxDepth(1);

where ProductCategory is a data entity, retrieved from DB that has a navigational prop to Company, not required and not needed when creating a new ProductCategory.

Best, Simo