AutoMapper设置属性为null目标对象上 [英] AutoMapper settings properties to null on destination object

查看:1474
本文介绍了AutoMapper设置属性为null目标对象上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的事情:

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; }
}

和下面的映射配置:

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());

要获得我用从DomainEntity的ApiEntity VAR apiEntity =映射.MAP< DomainEntity,ApiEntity>(myDomainEntity);

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

要从我使用的是ApiEntity获得合并DomainEntity VAR domainEntity = Mapper.Map(myApiEntity,myDomainEntity);

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

但是,当使用此,属性 OtherEntities AnotherEntities 设置为 - 甚至当他们呼吁从映射之前有值 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?

感谢您的帮助。

推荐答案

我认为你正在寻找 UseDestinationValue 而不是忽略

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());

这篇关于AutoMapper设置属性为null目标对象上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆