AutoMapper从枚举映射到自定义字符串值

时间:2018-06-18 18:54:17

标签: c# automapper

我正在进行迁移过程,我的任务是将此类实体迁移到声明

public class UserProperty
{
    public int Id { get; set; }
    public int UserId { get; set; }
    public Property Property { get; set; }
    public string PropertyValue { get; set; }
}

My Property enum:

public enum Property
{
    FirstName,
    LastName,
    Country
}

我想将Property映射到ClaimTypes。确切地说:

Property.FirstName = ClaimTypes.GivenName ("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname")
Property.LastName = ClaimTypes.Surname ("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname")
Property.Country = ClaimTypes.Country ("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/country")

我只使用AutoMapper进行基本转换,这让我很头疼。我知道我可能不得不使用.ForMember()。我现在已经走到这一步了:

cfg
    .CreateMap<Property, string>().ConvertUsing(value =>
    {
        switch (value)
        {
            case Property.FirstName:
                return ClaimTypes.GivenName;
            case Property.LastName:
                return ClaimTypes.Surname;
            case Property.Country:
                return ClaimTypes.Country;
            default:
                return null;
        }
    });

cfg
    .CreateMap<UserProperty, Claim>()
    .ConstructUsing(x => new Claim(x.Property, x.PropertyValue));

但是我在最后一行得到了一个红色的波浪形。

我也有一个想法,我可以使用一个简单的字典并通过枚举查找:

public class PropertyDictionary
{
    public Dictionary<Property, string> Map {
        get {
            return new Dictionary<Property, string>
            {
                { Property.FirstName, ClaimTypes.GivenName },
                { Property.LastName, ClaimTypes.Surname },
                { Property.Country, ClaimTypes.Country }
            };
        }
    }
}

var config = new MapperConfiguration(cfg =>
{
    var dict = new PropertyDictionary();

    cfg
        .CreateMap<UserProperty, Claim>()
        .ConstructUsing(x => new Claim(dict.Map[x.Property], x.PropertyValue));
});

虽然这有效,但我的同事建议去AutoMapper,所以我很好奇我将如何使用它。

0 个答案:

没有答案