Local Method Calls inside a Linq query - C#

Feb 20, 2019 BY xtreme

LINQ

Language INtegrated Queries are SQL-like C# queries that can be used to manipulate collections of objects. You can call user-defined functions inline. functions that are included in a query whose execution is deferred are not executed until the query is executed.


public async Task<IEnumerable<CommentModel>> Get()
{
    var query = from cmt in _context.Comment.AsQueryable()                        
                orderby cmt.CreatedOn descending
                select new CommentModel
                {
                    Id = cmt.Id,
                    Comment = cmt.Comment,                           
                    IsPublished = cmt.IsPublished,
                    IsDeleted = cmt.IsDeleted,
                    Associate = GetDetails(cmt.Id,cmt.AssociateType)
                };
    return await query.ToListAsync();
}


private AssociateModel GetDetails(string id, string type)
{
    switch (type)
    {
        case "T1":
            return _context.T1.AsQueryable()
                .Where(a => a.Id == id)
                .Select(a => new AssociateModel
                {
                    Id = a.Id,
                    Name = a.Title,
                    Type = "T1"
                }).FirstOrDefault<AssociateModel>();
        case "T2":
            return _context.T2.AsQueryable()
                .Where(a => a.Id == id)
                .Select(a => new AssociateModel
                {
                    Id = a.Id,
                    Name = a.Title,
                    Type = "T2"
                }).FirstOrDefault<AssociateModel>();
        default:
            return null;
    }
}

Related