空源为目标创建空对象

时间:2018-11-22 10:36:03

标签: c# .net-core automapper

我正在将Automapper 7.0.1与.Net core 2.1一起使用。

此类转换为

public class Item
{
    public long Id { get; set; }
    public int? CurrencyId { get; set; }

    public Location Location { get; set; } = null;
}

public class ItemLocation 
{
    public long Id { get; set; }

    public string Address { get; set; }

    [NotMapped]
    public Translation Translations { get; set; }

    public bool IsPrivate { get; set; } = false;                 

    public IList<ItemLocationUserDefined> UserDefinedItemLoacation { get; set; }

    [NotMapped]
    public float Latitude { get; set; }

    [NotMapped]
    public float Longitude { get; set; }
}

转换为:

public class ItemsToReturnDto
{
    public long Id { get; set; }
    public int? CurrencyId { get; set; }

    public LocationDto Location { get; set; } = null;
}

public class ItemLocationToReturnDto
    {
        public long Id { get; set; }

        public string Address { get; set; }

        public Translation Translations { get; set; }

        public float Latitude { get; set; }

        public float Longitude { get; set; }

        public bool IsUserDefined { get; set; }

        public DateTimeOffset UpdatedAt { get; set; }

        public DateTimeOffset CreatedAt { get; set; }
        public bool Disabled { get; set; }
    }

我已经在startup.cs中初始化了Automapper

var mappingConfig = new MapperConfiguration(mc =>
{
    mc.AllowNullDestinationValues = true;
    mc.AddProfile(new MappingProfile());
});

IMapper mapper = mappingConfig.CreateMapper();
services.AddSingleton(mapper);

映射个人资料:

CreateMap<ItemsToReturnDto, Item>()
                .ForMember(dest => (int)dest.Status, opts => opts.MapFrom(src => src.Status))
                .ReverseMap();
CreateMap<ItemLocationToReturnDto, ItemLocation>()
                .ForMember(dest => dest.IsPrivate, opts => opts.MapFrom(src => src.IsUserDefined))
                .ReverseMap();

但是,即使源Location对象为null,Automapper也会自动初始化空的Location对象。

如果源为空,如何返回空?

0 个答案:

没有答案