Home > OS >  Linq variable inside select
Linq variable inside select

Time:10-26

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

CodePudding user response:

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();   

CodePudding user response:

you can use it like this example

    List<string> someList= new List<string>();
    someList= someList.Select(x =>
    {
        var newVariable= "newVariable";
        return newVariable;
}).ToList();

in your case

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