Missing type map configuration or unsupported mapp

2019-07-18 12:49发布

问题:

I have a simple class:

[DataContract]
public class ClaimView
{
    [DataMember]
    public string Type { get; set; }

    [DataMember]
    public string Value { get; set; }

    [DataMember]
    public string ValueType { get; set; }
}

I receive this class on the client side by wcf server references and try to map it to System.Security.Claims.Claim like that:

    Mapper.CreateMap<ClaimView, Claim>()
      .ForMember(dest => dest.Type, opt => opt.MapFrom(src => src.Type)) 
      .ForMember(dest => dest.Value, opt => opt.MapFrom(src=> src.Value))
      .ForMember(dest => dest.ValueType, opt => opt.MapFrom(src => src.ValueType))
      .ForMember(dest => dest.Issuer, opt => opt.Ignore())
      .ForMember(dest => dest.OriginalIssuer, opt => opt.Ignore())
      .ForMember(dest => dest.Properties, opt => opt.Ignore())
      .ForMember(dest => dest.Subject, opt => opt.Ignore());

After I've got the error from autommaper he can't to convert it. What's missing or wrong?

回答1:

Because Claim doesn't have a default constructor, you need to tell Automapper which constructor to use, e.g.:

  Mapper.CreateMap<ClaimView, Claim>()

        .ConstructUsing(cv => new Claim(cv.Type, cv.Value, cv.ValueType))

        .ForMember(dest => dest.Type, opt => opt.MapFrom(src => src.Type))
        .ForMember(dest => dest.Value, opt => opt.MapFrom(src => src.Value))
        .ForMember(dest => dest.ValueType, opt => opt.MapFrom(src => src.ValueType))
        .ForMember(dest => dest.Issuer, opt => opt.Ignore())
        .ForMember(dest => dest.OriginalIssuer, opt => opt.Ignore())
        .ForMember(dest => dest.Properties, opt => opt.Ignore())
        .ForMember(dest => dest.Subject, opt => opt.Ignore());

Then this test will pass:

public void Test()
{
     ClaimIdentityView civ = new ClaimIdentityView
     {
         ClaimViewList = new List<ClaimView> 
                             {
                                 new ClaimView 
                                 {
                                      Type = "type", 
                                      Value = "val", 
                                      ValueType = "string"
                                  }
                             }
     };

     var claims = civ.ClaimViewList.Select(Mapper.Map<ClaimView, Claim>).ToList();

     Assert.AreEqual(1, claims.Count);

     Assert.AreEqual("type", claims.Single().Type);
     Assert.AreEqual("val", claims.Single().Value);
     Assert.AreEqual("string", claims.Single().ValueType);
}