Search code examples
c#linqentity-framework-core

Linq variable inside select


I have a following query

 return _context.Table1
                    .Where(x => x.ContactId == contactKey.Id)                       
                    .Include(x => x.Table2)                        
                    .Include(x => x.Table3.Table4)
                    .Select(a =>
                        new MyReadModel
                        {                               
                            PriorityAssignment = true,
                            LastContactedDate = (a.Table3.Table4 != null && a.Table3.Table4.FirstOrDefault(h => 
                            h.Id == a.Table2.FkId
                            ) != null ?
                            a.Table3.Table4.FirstOrDefault(h => && h.Id == a.Table2.FkId
                            ).LastContactedDatetime : default
                            )
                        }
                     )
                    .ToListAsync();

What i wants is to simplify LastContactedDate assignment with in select. I think we can assign

a.Table3.Table4.FirstOrDefault(h => 
                                h.Id == a.Table2.FkId
                                )

to some variable but can't able to do it can someone identify what is needed


Solution

  • With EF Core you don't have to check for null, LINQ Translator do not execute your code, but uses it for translation to the SQL. Also Includes is not needed if you do not retrieve whole objects.

    return await _context.Table1
        .Where(x => x.ContactId == contactKey.Id)                       
        .Select(a => new MyReadModel
        {                               
            PriorityAssignment = true,
            LastContactedDate = (DateTime?)a.Table3.Table4.Where(h => h.Id == a.Table2.FkId)
                .OrderByDescending(h => LastContactedDatetime)
                .Select(h => LastContactedDatetime)
                .FirstOrDefault()
        }).ToListAsync();