如何获取使用AutoMapper映射的属性的属性名称?

时间:2019-02-04 11:18:08

标签: c# automapper

我有以下课程:

public class FooEntity {
   public Guid Member1 { get; set; }
   public Guid Member2 { get; set; }
}

public class FooDomain {
   public PhotoId Member1 { get; set; }
   public ExifId Member2 { get; set; }
}

public sealed class PhotoId : RequiredGuid
{
    private const string Name = "PhotoId";

    public PhotoId(Guid guid) : base(Name, guid)
    {
    }

    public static implicit operator PhotoId(Guid guid)
    {
        return new PhotoId(guid);
    }
}

public sealed class ExifId : RequiredGuid
{
    private const string Name = "ExifId";

    public ExifId(Guid guid) : base(Name, guid)
    {
    }

    public static implicit operator ExifId(Guid guid)
    {
        return new ExifId(guid);
    }
}

public class RequiredGuid {
    private string _name;
    private string _guid;

    public RequiredGuid(string name, Guid guid)
    {
        if (guid == Guid.Empty)
            throw new GuidShouldNotBeEmptyException($"The '{name}' field is required");

       _name = name;
       _guid = guid;
    }

    public static implicit operator Guid(RequiredGuid field)
    {
        return _guid;
    }

}

和个人资料中:

CreateMap<FooEntity, FooDomain>().ReverseMap();
CreateMap<RequiredGuid, Guid>().ConvertUsing(src => src); //calls implicit operator

然后我想展开我的RequiredGuid属性

CreateMap<Guid, RequiredGuid>().ConvertUsing<GuidConverter>();

转换器:

public class GuidConverter : ITypeConverter<Guid, RequiredGuid>
{
    public RequiredGuid Convert(Guid source, RequiredGuid destination, ResolutionContext context)
    {
        var propertyNameBeingMapped = ???;

        return new RequiredGuid(propertyNameBeingMapped, source);
    }
}

当我转换FooDomain => FooEntity时,我具有RequiredGuid => Guid:好的。

当我转换FooEntity => FooDomain,Guid => RequiredGuid时,我无法获得属性名称。

我认为我应该使用ResolutionContext,但是如何使用?

谢谢!

0 个答案:

没有答案