2015-11-26 56 views
0

我有代碼,它使用userClass轉換器。我想用automapper來做同樣的事情。如何重寫代碼?通過轉換器自動映射器

public static ClaimIdentityView ConvertToClaimIdentityView(this ClaimsIdentity Identity) 
{ 
    ClaimIdentityView result = new ClaimIdentityView() 
    { 
     Name = Identity.Name, 
     NameClaimType = Identity.NameClaimType, 
     AuthenticationType = (AuthenticationTypeEnum)EnumStringValue.Parse(typeof(AuthenticationTypeEnum), Identity.AuthenticationType), 
     RoleClaimType = Identity.RoleClaimType 
    }; 
    foreach (Claim item in Identity.Claims) 
     result.ClaimViewList.Add(item.ConvertToClaimView()); 
    return result; 
} 
public static ClaimView ConvertToClaimView(this Claim Claim) 
{ 
    return new ClaimView() 
    { 
     Type = Claim.Type, 
     Value = Claim.Value, 
     ValueType = Claim.ValueType 
    }; 
} 

和所述第二類(第一個是從System.Security.Claims;命名空間):

public class ClaimIdentityView 
{ 
    public ClaimIdentityView() 
    { 
     ClaimViewList = new List<ClaimView>(); 
    } 
    public Guid UserId { get; set; } 
    public AuthenticationTypeEnum AuthenticationType { get; set; } 
    public IList<ClaimView> ClaimViewList { get; set; } 
    public string Name { get; set; } 
    public string NameClaimType { get; set; } 
    public string RoleClaimType { get; set; } 
} 

回答

1

映射是這樣的:

AutoMapper.Mapper.CreateMap<ClaimsIdentity, ClaimIdentityView>() 
    .ForMember(dest => dest.ClaimViewList, opt => opt.MapFrom(src => src.Claims)) 
    .ForMember(dest => dest.AuthenticationType, 
     opt => opt.MapFrom(src => (AuthenticationTypeEnum) 
     EnumStringValue.Parse(typeof (AuthenticationTypeEnum), src.AuthenticationType))); 

AutoMapper.Mapper.CreateMap<Claim, ClaimView>(); 

實施例映射代碼:

var claimIdentity = new ClaimsIdentity(WindowsIdentity.GetCurrent()); 
var view = AutoMapper.Mapper.Map<ClaimsIdentity, ClaimIdentityView>(claimIdentity); 

This tes t然後會通過:

var claimIdentity = new ClaimsIdentity(WindowsIdentity.GetCurrent()); 
// realistically the current account will have claims, but.. 
claimIdentity.AddClaim(new Claim("Type", "Value")); 
var view = AutoMapper.Mapper.Map<ClaimsIdentity, ClaimIdentityView>(claimIdentity); 

Assert.IsTrue(view.ClaimViewList.Count > 0); 
+0

是的,但如何在映射ClaimView期間填寫ClaimViewList? automapper是否支持委託或什麼? – user3818229

+0

ClaimViewList是ClaimViews的列表,AutoMapper知道如何將Claim映射到ClaimView,以及如何將列表映射到列表。我忘了添加一個告訴AutoMapper如何鏈接屬性的位,因爲它們有不同的名稱,我編輯了答案。 – stuartd

+0

我的意思是說你錯過了這個循環: foreach(Identity.Claims中的聲明項) result.ClaimViewList.Add(item.ConvertToClaimView());因此,我需要這樣做: /.../.AfterMap((src,dest)=> dest.ClaimViewList.Concat(src.Claims)); 但我不知道如何正確使用它。 – user3818229