Christy Pirumova
Christy Pirumova

Reputation: 169

Automapper 2 source fields mapped to 1 destination field

I have 2 classes to be mapped: class1 has fields PaymentState and PaymentStateId

public int PaymentStateId { get; set; }
        
[ForeignKey(nameof(PaymentStateId))]
[InverseProperty(nameof(PaymentStateEntity.OrderEntities))]
public virtual PaymentStateEntity PaymentState { get; set; }

class2 has field with the same name PaymentState but of enum type

public PaymentState PaymentState { get; set; }

while mapping class1 to class2 there is an error that field PaymentState cannot be mapped:

Unable to create a map expression from
class1.PaymentState (Entities.PaymentStateEntity) to PaymentState.PaymentState (Enums.PaymentState)

Mapping types:

class1-> class2

Destination Member:

PaymentState

have tried custom mapping fields, but I guess that the fact that there are 2 fields now which are to be mapped to 1 destication field makes the problem

CreateMap<class1, class2>()
                .ForMember(dest => dest.PaymentState, opt => opt.MapFrom(src => src.PaymentStateId))

What is the way to ignore one source field though let another source field to be mapped to destination field?

Upvotes: 0

Views: 884

Answers (1)

Jihai
Jihai

Reputation: 110

I don't think the error cause is 2 fields mapped into 1 destination. Probably because of the difference of type between dest and source. You should check log what the error is. But you can try to use

CreateMap<class1, class2>()
.ForMember(dest => dest.PaymentState, opt => opt.Ignore())
.ForMember(dest => dest.PaymentState, opt => opt.MapFrom(src => src.PaymentStateId))

Besides, you can convert 2 enums by setting their items to have the same value

.ForMember(dest => dest.PaymentState, opt => opt.MapFrom(src => (PaymentState)((int)src.PaymentState)))

Upvotes: 2

Related Questions