Hello everyone I am trying to achieve something relatively simple in Automapper but I keep on failing. I am trying to map a property on my Dto with a function expression
.ForMember(dest => dest.HasPaid, opt => opt.MapFrom(c => MapHasPaid(c)))
private bool MapHasPaid(AppUser src)
{
var lastPayment = src.RentPayments.OrderByDescending(p => p.DateTo).FirstOrDefault();
if (lastPayment == null)
{
return false;
}
return lastPayment.DateFrom.Date <= DateTime.Now.Date &&
DateTime.Now.Date <= lastPayment.DateTo.Date;
}
This returns
LINQ to Entities does not recognize the method 'Boolean MapHasPaid(xxxx.Models.AppUser)' method, and this method cannot be translated into a store expression.
I tried with a IValueResolver
public class CustomResolver : IValueResolver<AppUser, HouseMateEntity, bool>
{
public bool Resolve(AppUser source, HouseMateEntity destination, bool member, ResolutionContext context)
{
var lastPayment = source.RentPayments.OrderByDescending(p => p.DateTo).FirstOrDefault();
if (lastPayment == null)
{
return false;
}
return lastPayment.DateFrom.Date <= DateTime.Now.Date &&
DateTime.Now.Date <= lastPayment.DateTo.Date;
}
}
.ForMember(dest => dest.HasPaid, opt => opt.ResolveUsing<CustomResolver>())
but give me the following exception
Can't resolve this to Queryable Expression
How can I map my property as a result of more complex query?
thanks
I have also tried the simple case on the documentation https://github.com/AutoMapper/AutoMapper/wiki/Custom-value-resolvers
same error exception
Can't resolve this to Queryable Expression
Has anyone got ResolveUsing to work? is this an automapper bug?
EDIT: the only way I could get this working is with the following, and it really smells bad to me
.ForMember(dest => dest.HasPaid,
opt => opt.MapFrom(c => DbFunctions.TruncateTime(c.RentPayments.OrderByDescending(p => p.DateTo).FirstOrDefault().DateFrom) <= DbFunctions.TruncateTime(DateTime.Now) &&
DbFunctions.TruncateTime(DateTime.Now) <= DbFunctions.TruncateTime(c.RentPayments.OrderByDescending(p => p.DateTo).FirstOrDefault().DateTo)));