跳过映射的空属性

跳过映射的空属性

本文介绍了跳过映射的空属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用AutoMapper将ViewModel映射到模型.但是,如果相应的源属性为null,我希望属性不被映射.

I'm using AutoMapper to map a ViewModel to a Model. However, I want properties to not be mapped if the corresponding source property is null.

我的源类如下:

public class Source
{
    //Other fields...
    public string Id { get; set; } //This should not be mapped if null
}

目标类是:

public class Destination
{
    //Other fields...
    public Guid Id { get; set; }
}

这是我配置映射器的方式:

And here is how I configured the mapper:

Mapper.Initialize(cfg =>
{
    //Other mappings...
    cfg.CreateMap<Source, Destination>()
        .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null));
});

我认为,映射将意味着,如果源为null,则目标中的属性不会被覆盖.但是显然我错了:即使Source.Id为null,它仍然会被映射,AutoMapper会为其分配一个空的Guid(00000000-0000-0000-0000-000000000000),覆盖现有的Guid.如果源为null,如何正确告诉AutoMapper跳过属性的映射?

I thought that mapping would mean that properties don't get overwritten in the destination if the source one is null. But apparently I'm wrong: even when Source.Id is null, it still gets mapped, AutoMapper assigns it an empty Guid (00000000-0000-0000-0000-000000000000), overwriting the existing one. How do I properly tell AutoMapper to skip mapping of a property if the source is null?

注意:我不认为Guid<->String转换有问题,这种转换在automapper中有效,我在传递中使用了它.问题在于,当它为null时,它不会跳过Id属性.

NOTE: I don't think this is a problem with the Guid<->String conversion, such conversion works in automapper, I've used it in the pass. The problem is that it's not skipping the Id property when it is null.

推荐答案

简单的方法是不必区分null和Guid.Empty.像这样

The easy way would be to not have to distinguish between null and Guid.Empty. Like this

    cfg.CreateMap<Source, Destination>()
        .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => ((Guid)srcMember) != Guid.Empty));

在这种情况下,源成员不是您要映射的字符串值,而是分配给目标的解析值.它的类型为Guid,是一个结构,因此永远不会为null.空字符串将映射到Guid.Empty.请参见此处.

In this case the source member is not the string value you map from, it's the resolved value that would be assigned to the destination. It's of type Guid, a struct, so it will never be null. A null string will map to Guid.Empty. See here.

这篇关于跳过映射的空属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 21:03