Type checking fails for GroupJoin with DefaultIfEmpty followed by SelectMany

Open
#12,606 5 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
25/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Stale
Tech stack
csharp, sqlite
Domain
database

Research direction

Start with the GroupJoin, DefaultIfEmpty, and SelectMany query in the reproduction's Program.Main and run it against the SQLite context. Trace the query translation and executor-lambda creation involved in the reported exception. Done means the left-join query type-checks and executes without the ArgumentException, returning the expected parent and child results.

Written by the indexing model from the issue text.

Description

area-query customer-reported

Attempting to model a left join, but type checking fails.

System.ArgumentException: Expression of type 'System.Collections.Generic.IEnumerable`1[Test.Child]' cannot be used for return type 'System.Collections.Generic.IEnumerable`1[<>f__AnonymousType1`2[Test.Parent,Test.Child]]'
   at System.Linq.Expressions.Expression.ValidateLambdaArgs(Type delegateType, Expression& body, ReadOnlyCollection`1 parameters, String paramName)
   at System.Linq.Expressions.Expression.Lambda[TDelegate](Expression body, String name, Boolean tailCall, IEnumerable`1 parameters)
   at System.Linq.Expressions.Expression.Lambda[TDelegate](Expression body, Boolean tailCall, IEnumerable`1 parameters)
   at System.Linq.Expressions.Expression.Lambda[TDelegate](Expression body, ParameterExpression[] parameters)
   at Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor.CreateExecutorLambda[TResults]()
   at Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor.CreateQueryExecutor[TResult](QueryModel queryModel)
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](Expression query, IQueryModelGenerator queryModelGenerator, IDatabase database, IDiagnosticsLogger`1 logger, Type contextType)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass13_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQueryCore[TFunc](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
   at Remotion.Linq.QueryableBase`1.GetEnumerator()
   at System.Collections.Generic.LargeArrayBuilder`1.AddRange(IEnumerable`1 items)
   at System.Collections.Generic.EnumerableHelpers.ToArray[T](IEnumerable`1 source)
   at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
   at Test.Program.Main() in C:\Users\User\Documents\Visual Studio 2017\Projects\Test\Test\Program.cs:line 38
Steps to reproduce
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;

namespace Test
{
    class Program
    {
        static void Main()
        {
            var connection = new Microsoft.Data.Sqlite.SqliteConnection("Data Source=:memory:");
            connection.Open();

            var options = new DbContextOptionsBuilder<TestContext>()
                .UseSqlite(connection)
                .Options;

            using (var dbContext = new TestContext(options))
            {
                dbContext.Database.EnsureCreated();
            }

            using (var dbContext = new TestContext(options))
            {
                var query = dbContext.Parents
                    .GroupJoin(dbContext.Children, p => p.ParentId, c => c.ParentId, (p, c) => new
                    {
                        Parent = p,
                        Children = c.DefaultIfEmpty(),
                    })
                    .SelectMany(e => e.Children.Select(c => new
                    {
                        e.Parent,
                        Child = c,
                    }));

                var result = query.ToArray();
            }
        }
    }

    internal class TestContext : DbContext
    {
        public TestContext(DbContextOptions options)
            : base(options)
        {
        }

        public DbSet<Parent> Parents { get; set; }

        public DbSet<Child> Children { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Child>()
                .HasOne(c => c.Parent)
                .WithMany(p => p.Children)
                .HasForeignKey(c => c.ParentId);
        }
    }

    internal class Parent
    {
        [Key]
        public int ParentId { get; set; }

        public List<Child> Children { get; set; }
    }

    internal class Child
    {
        [Key]
        public int ChildId { get; set; }

        public int ParentId { get; set; }
        public Parent Parent { get; set; }
    }
}
Further technical details

EF Core version: 2.1.1
Database Provider: Microsoft.EntityFrameworkCore.Sqlite
Operating system: Windows 10
IDE: Visual Studio 2017 15.7.4

Dominant language
C#
Stars
14.8k
Forks
3.4k
Avg merge
2d 5h
Merged PRs (30d)
134

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from dotnet/efcore

All issues in dotnet/efcore

Similar issues

More C# issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.