C# AutoMapper ,Change Mapper Setting on Fly

1k views Asked by At

This is my Domain Object Type

[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; }
}

And this is my Data Transfer Objet

[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>();
    }
}

When I map CreateCredentialingCallDetailInput to CredentialingCallDetail i.e

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

I get the exception enter image description here

There is a mismatch between the type of Id , Automapper is not mapping string to ObjectId,Is There any way i can change the setting on fly , i.e change setting to ignore Id Mapping ?

1

There are 1 answers

0
mfahadi On BEST ANSWER

Answer can be found in this question (yes question!). You can do this in two ways.Check the question for details.

Quick answer for you.

You can ignore extra elements when defining mapping.

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

Just add 2nd line to your existing mapping.

This looks ambiguous,

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

Should not it be something like this

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