'Cannot convert lambda expression to type 'IValueResolver<Entity, MyDto, object>' because it is not a delegate type

I am trying to define this simple mapping in my profile

CreateMap<CompanyClient, MyDto>() 
.ForMember(
    dto => dto.PaymentTerms,
    opt => opt.MapFrom(companyClient => companyClient.Company.PaymentTerms != null
        ? companyClient.Company.PaymentTerms.Value
        : null))

But I'm getting this stupid error message:

Cannot convert lambda expression to type 'IValueResolver<CompanyClient, MyDto, object>' because it is not a delegate type

What exacly is the problem here? I have used plenty of ternary operators elsewhere in my code, but for some reason this nullable SmartEnum case has some kind of problem

entity:

public sealed class CompanyClient
{
    ...
    Public PaymentTerm? PaymentTerms { get; private set; }
    ...
}

dto:

public sealed record MyDto
{
    ...
    Public int? PaymentTerms { get; private init; }
    ...
}

PaymentTerm.cs is just a simple SmartEnum

Note that it does not give any compiler errors when I write it like this:

.ForMember(
    dto => dto.PaymentTerms,
    opt => opt.MapFrom(companyClient => companyClient.Company.PaymentTerms ?? null))

or

.ForMember(
    dto => dto.PaymentTerms,
    opt => opt.MapFrom(companyClient => companyClient.Company.PaymentTerms))

What is the problem?



Solution 1:[1]

I found that we can get rid of this stupid message by just casting the non-null result to the output type.

So where

.ForMember(
    dst => dst.VisitReportFileId,
    opt => opt.MapFrom(src => src.VisitReportFile == null 
        ? null 
        : src.VisitReportFile.Id.Key));

Gives me a

Cannot convert lambda expression to type 'IValueResolver<Activity, ActivityDTO, object>' because it is not a delegate type

I can fix it by casting the "else" result to Guid?:

.ForMember(
    dst => dst.VisitReportFileId,
    opt => opt.MapFrom(src => src.VisitReportFile == null 
        ? null 
        : (Guid?)src.VisitReportFile.Id.Key));

Solution 2:[2]

The reason for your error is that the conditional operator (c ? t : f) takes precedence over the lambda declaration (=>). source

Wrapping the conditional operator in {} brackets should solve your problem:

CreateMap<CompanyClient, MyDto>() 
.ForMember(
    dto => dto.PaymentTerms,
    opt => opt.MapFrom(companyClient => 
    {
        companyClient.Company.PaymentTerms != null
            ? companyClient.Company.PaymentTerms.Value
            : null
    }))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bassie
Solution 2 Martijn Willems