Home > front end >  Write from/group in method instead of query syntax in efcore
Write from/group in method instead of query syntax in efcore

Time:05-20

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,
        //...
    };

CodePudding user response:

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.

  • Related