Home > Mobile >  Cannot convert lambda expression to type 'object'
Cannot convert lambda expression to type 'object'

Time:01-07

How can I get this Lambda expression to work in Entity Framework?

Basically, if there is a goalCyleId, then look it up and get the end date of it.

.Select(x => new GoalDTO()
{
    GoalId = x.GoalId,
    Name = x.Name,
    DueDate = x.GoalCycleId == null ? null : _context.GoalCycles.Find(y => y.GoalCycleId == x.GoalCycleId).EndDate

})

I'm getting the error "Cannot convert lambda expression to type 'object' because it is not a delegate type"

CodePudding user response:

Try to use the below query,

.Select(x => new GoalDTO() {
  GoalId = x.GoalId,
    Name = x.Name,
    DueDate = x.GoalCycleId == null ? null : _context.GoalCycles.FirstOrDefault(y => y.GoalCycleId == x.GoalCycleId).EndDate

})

CodePudding user response:

If your entities are set up with the navigation properties, you should just need something like:

.Select(x => new GoalDTO()
{
    GoalId = x.GoalId,
    Name = x.Name,
    DueDate = x.GoalCycle.EndDate
})

GoalCycleId on the Goal may be Null-able, so a GoalCycle navigation reference may be #null but when EF projects this down it would leave DueDate #null if there is no GoalCycle for that Goal, otherwise taking the End Date. However, that would trip a NullReferenceException if the Select is being done after the EF query is materialized. (I.e. premature ToList())

It shouldn't complain with:

DueDate = x.GoalCycle?.EndDate
  • Related