Search code examples
entity-frameworklinq

Write from/group in method instead of query syntax in efcore


How can this query syntax be translated into method syntax?

var query =
    from a in _dbContext.A
    from b in a.B.DefaultIfEmpty()
    from c in a.C.DefaultIfEmpty()
    group new { b, c } by new
    {
        Id = a.Id.ToString(),
        a.Name,
        //...
    } into g
    select new SomeDto
    {
        Id = g.Key.Id,
        Name = g.Key.Name,
        //...
    };

Solution

  • Well, this how it looks in Method Chain syntax:

    var uglyQuery = _dbContext.A
        .SelectMany(a => a.B.DefaultIfEmpty(), (a, b) => new { a, b })
        .SelectMany(t => t.a.C.DefaultIfEmpty(), (t, c) => new { t, c })
        .GroupBy(x => new
        {
            Id = x.t.a.Id.ToString(), 
            x.t.a.Name,
            //...
        }, x => new { x.t.b, x.c })
        .Select(g => new SomeDto
        {
            Id = g.Key.Id, 
            Name = g.Key.Name,
            //...
        });
    

    Note that this conversion is available in ReSharper in context menu Convert to LINQ method chain.