C#AutoMapper,在飞行中更改映射器设置

时间:2016-12-28 11:20:01

标签: c# automapper bson

这是我的域对象类型

[Table("CredentialingCallDetail")]
[BsonIgnoreExtraElements]
public class CredentialingCallDetail : FullAuditedEntity<ObjectId>
{ 
    public string RepresentativeName { get; set; }
    public string PhoneNumber { get; set; }
    public string PhoneExtension { get; set; }
    public string CallResultStatus { get; set; }
    public string IsFacilityCredentialed { get; set; }
    public string Provider { get; set; }
    public string PIN { get; set; }
    public List<LicensedProfessionalCredentialed> LicensedProfessionalCredentials { get; set; }
}

这是我的数据传输对象

[AutoMapTo(typeof(CredentialingCallDetail))]
public class CreateCredentialingCallDetailInput
{    
    [BsonIgnore]
    public string Id { get; set; }
    [Required]
    public string RepresentativeName { get; set; }
    [Required]
    public string PhoneNumber { get; set; }
    public string PhoneExtension { get; set; }
    [Required]
    public string CallResultStatus { get; set; }
    public string IsFacilityCredentialed { get; set; }
    public string Provider { get; set; }
    public string PIN { get; set; }
    public string Status  { get; set; }
    public List<LicensedProfessionalCredentialedDto> LicensedProfessionalCredentials { get; set; }
    public CreateCredentialingCallDetailInput()
    {
        LicensedProfessionalCredentials = new List<LicensedProfessionalCredentialedDto>();
    }
}

当我将CreateCredentialingCallDetailInput映射到CredentialingCallDetail,即

CredentialingCallDetail newCredentialingCallDetail = input.CredentialingCallDetail.MapTo<CredentialingCallDetail>();

我得到了例外 enter image description here

Id的类型不匹配,Automapper没有将字符串映射到ObjectId,有没有办法可以在飞行中更改设置,即更改设置以忽略Id Mapping?

1 个答案:

答案 0 :(得分:2)

答案可以在this问题中找到(是的问题!)。 您可以通过两种方式执行此操作。请查看详细信息。

快速回答。

定义映射时可以忽略额外的元素。

 CreateMap<CreateCredentialingCallDetailInput, CredentialingCallDetail >()
.ForSourceMember(src => src.Id, opt => opt.Ignore())

只需在现有映射中添加第二行。

这看起来很模糊,

CredentialingCallDetail newCredentialingCallDetail =
input.CredentialingCallDetail.MapTo<CredentialingCallDetail>();

不应该是这样的

CredentialingCallDetail newCredentialingCallDetail =
CreateCredentialingCallDetailInput.MapTo<CredentialingCallDetail>();