dotnet / efcore

EF Core is a modern object-database mapper for .NET. It supports LINQ queries, change tracking, updates, and schema migrations.
https://docs.microsoft.com/ef/
MIT License
13.79k stars 3.19k forks source link

Expression passed to the Include operator could not be bound #2048

Closed keraxel closed 9 years ago

keraxel commented 9 years ago

Including specified entity throws exception: InvalidOperationException: The expression '[100001].Owner' passed to the Include operator could not be bound.

Reproduction steps:

  1. Clone https://github.com/Keraxel/EfIncludeBug
  2. Apply migrations (cd src\EfBugProof && k ef migration apply)
  3. Run
  4. Go to /Pages

My environment:

Full stacktrace:

InvalidOperationException: The expression '[100001].Owner' passed to the Include operator could not be bound.
Microsoft.Data.Entity.Query.EntityQueryModelVisitor.IncludeNavigations(QueryModel queryModel, Type resultType)
Microsoft.Data.Entity.Query.EntityQueryModelVisitor.CreateAsyncQueryExecutor[TResult](QueryModel queryModel)
Microsoft.Data.Entity.Relational.RelationalDataStore.AsyncQuery[TResult](QueryModel queryModel, CancellationToken cancellationToken)
Microsoft.Data.Entity.Query.EntityQueryExecutor.AsyncExecuteCollection[T](QueryModel queryModel, CancellationToken cancellationToken)
Microsoft.Data.Entity.Query.EntityQueryProvider.AsyncQuery[T](Expression expression)
Microsoft.Data.Entity.Query.EntityQueryable`1.System.Collections.Generic.IAsyncEnumerable<TResult>.GetEnumerator()
System.Linq.AsyncEnumerable.Aggregate[TSource,TAccumulate,TResult](IAsyncEnumerable`1 source, TAccumulate seed, Func`3 accumulator, Func`2 resultSelector, CancellationToken cancellationToken)
System.Linq.AsyncEnumerable.Aggregate[TSource,TAccumulate](IAsyncEnumerable`1 source, TAccumulate seed, Func`3 accumulator, CancellationToken cancellationToken)
System.Linq.AsyncEnumerable.ToList[TSource](IAsyncEnumerable`1 source, CancellationToken cancellationToken)
System.Linq.QueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
System.Linq.QueryableExtensions.ToListAsync[TSource](IQueryable`1 source)
EfBugProof.Controllers.PagesController.<Index>d__0.MoveNext() in PagesController.cs
                var model3 = await model2.ToListAsync();
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
Microsoft.AspNet.Mvc.ControllerActionExecutor.<CastToObject>d__8`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
Microsoft.AspNet.Mvc.ControllerActionExecutor.<ExecuteAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
Microsoft.AspNet.Mvc.ControllerActionExecutor.<ExecuteAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
Microsoft.AspNet.Mvc.ControllerActionInvoker.<InvokeActionAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
Microsoft.AspNet.Mvc.FilterActionInvoker.<InvokeActionFilterAsync>d__41.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNet.Mvc.FilterActionInvoker.<InvokeAsync>d__32.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Mvc.MvcRouteHandler.<InvokeActionAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Mvc.MvcRouteHandler.<RouteAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Routing.Template.TemplateRoute.<RouteAsync>d__25.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Routing.RouteCollection.<RouteAsync>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Builder.RouterMiddleware.<Invoke>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Security.Infrastructure.AuthenticationMiddleware`1.<Invoke>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNet.Security.Infrastructure.AuthenticationMiddleware`1.<Invoke>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Security.Infrastructure.AuthenticationMiddleware`1.<Invoke>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNet.Security.Infrastructure.AuthenticationMiddleware`1.<Invoke>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Security.Infrastructure.AuthenticationMiddleware`1.<Invoke>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNet.Security.Infrastructure.AuthenticationMiddleware`1.<Invoke>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Security.Infrastructure.AuthenticationMiddleware`1.<Invoke>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNet.Security.Infrastructure.AuthenticationMiddleware`1.<Invoke>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
System.Threading.Tasks.TaskExtensions.CultureAwaiter.GetResult()
Microsoft.AspNet.Diagnostics.Entity.MigrationsEndPointMiddleware.<Invoke>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
System.Threading.Tasks.TaskExtensions.CultureAwaiter.GetResult()
Microsoft.AspNet.Diagnostics.Entity.DatabaseErrorPageMiddleware.<Invoke>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNet.Diagnostics.Entity.DatabaseErrorPageMiddleware.<Invoke>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Diagnostics.ErrorPageMiddleware.<Invoke>d__4.MoveNext()
damccull commented 9 years ago

I seem to be getting this same issue. I only see it in the popup when debugging my app and get no output anywhere else. This is called from a class that initializes the database and the method is called in Startup.Configure with this code:

//Seed the database
var destinySeeder = ActivatorUtilities.CreateInstance<DestinyDbInitializer>(app.ApplicationServices);
//If development, let's seed the database with debug values, else just seed normal values
destinySeeder.InitializeData(env.IsEnvironment("Development"));

The code that gets the exception is:

var raid1 = db.ScheduledRaids
                .Include(r => r.RaidMembers)
                .Where(r => r.ScheduledRaidId == 1).Single();

The error detail is:

System.InvalidOperationException was unhandled by user code
HResult=-2146233079
Message=The expression '[100001].RaidMembers' passed to the Include operator could not be bound.
Source=EntityFramework.Core
StackTrace:
   at Microsoft.Data.Entity.Query.EntityQueryModelVisitor.IncludeNavigations(QueryModel queryModel, Type resultType)
   at Microsoft.Data.Entity.Query.EntityQueryModelVisitor.CreateQueryExecutor[TResult](QueryModel queryModel)
   at Microsoft.Data.Entity.Relational.RelationalDataStore.CompileQuery[TResult](QueryModel queryModel)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.Data.Entity.Query.CompiledQueryCache.CompileQuery(IDataStore dataStore, MethodInfo compileMethodInfo, Type resultItemType, QueryModel queryModel)
   at Microsoft.Data.Entity.Query.CompiledQueryCache.<>c__4`1.<Execute>b__4_0(Expression q, IDataStore ds)
   at Microsoft.Data.Entity.Query.CompiledQueryCache.<>c__DisplayClass7_0.<GetOrAdd>b__0(ICacheSetContext c)
   at Microsoft.Framework.Caching.Memory.CacheExtensions.<>c__DisplayClass7_0`1.<Set>b__0(ICacheSetContext context)
   at Microsoft.Framework.Caching.Memory.MemoryCache.Set(String key, IEntryLink link, Object state, Func`2 create)
   at Microsoft.Framework.Caching.Memory.CacheExtensions.Set(IMemoryCache cache, String key, Object state, Func`2 create)
   at Microsoft.Framework.Caching.Memory.CacheExtensions.Set[T](IMemoryCache cache, String key, Object state, Func`2 create)
   at Microsoft.Framework.Caching.Memory.CacheExtensions.GetOrSet[T](IMemoryCache cache, String key, Object state, Func`2 create)
   at Microsoft.Data.Entity.Query.CompiledQueryCache.GetOrAdd(Expression query, QueryContext queryContext, IDataStore dataStore, Boolean isAsync, Func`3 compiler)
   at Microsoft.Data.Entity.Query.CompiledQueryCache.Execute[TResult](Expression query, IDataStore dataStore, QueryContext queryContext)
   at Microsoft.Data.Entity.Query.EntityQueryProvider.Execute[TResult](Expression expression)
   at System.Linq.Queryable.Single[TSource](IQueryable`1 source)
   at SaVyWebsite.DAL.DestinyDbInitializer.<AddMembersToRaids>d__32.MoveNext() in C:\Users\David\Projects\dotnet\SaVyWebsite\src\SaVyWebsite\DAL\DestinyDbInitializer.cs:line 383
InnerException:

There is no inner exception to look at.

anpete commented 9 years ago

This error occurs when any of the properties referenced in the the Include could not be found in the model. This would typically have happened early on because Code First wasn't fleshed out and so exhaustive model configuration was required.

Is anyone on this issue still having problems here? If not, I will close it as by design.

TheMadKow commented 9 years ago

I still got this error going for me on Beta7 (InvalidOperationException: The expression '[x].Next' passed to the Include operator could not be bound.)

in Microsoft.Data.Entity.Query.EntityQueryModelVisitor.b__29_0(IncludeQueryAnnotation annotation)

Have i missed anything ?

anpete commented 9 years ago

@TheMadKow, have you checked that the Next navigation property is part of your model?

TheMadKow commented 9 years ago

@anpete You are right, the FK wasn't created for the "Next" Property, but it was created for the "Prev" Property. Both are created now with the "Reference" function on the ModelBuilder. (Still Next FK is missing)

Is it relevant for this thread or in another one ?

anpete commented 9 years ago

@TheMadKow Please file a new bug for the issue, thanks.

ChangedHourly commented 9 years ago

Hi, I think I am seeing this issue, but only using the Fluent API. I just decided to move away from annotations in my model to using the Fluent API. Everything looked good until I hit this issue. The relevant part of my model contains a Donor who can make zero or more donations:

public class Donor : Person, IDonor
{
    public Donor() { }

    private ICollection<Donation> _donations;

    [InverseProperty("DonatedBy")]
    public virtual ICollection<Donation> Donations
    {
        get
        {
            if (_donations == null)
            {
                _donations = new Collection<Donation>();
            }
            return _donations;
        }
        set
        {
            _donations = value;
            NotifyPropertyChanged();
        }
    }

And the Donation class contains this code:

    public Guid DonatedBy_PersonId { get; set; }
    [InverseProperty("Donations")]
    [ForeignKey("DonatedBy_PersonId")]
    public virtual Donor DonatedBy
    {
        get
        {
            return _donor;
        }
        set
        {
            _donor = value;
        }
    }

This works OK. If I try to move to using the Fluent API:

        modelBuilder.Entity<Donor>().HasMany<Donation>().WithOne(d => d.DonatedBy);

        modelBuilder.Entity<Donation>().HasOne<Donor>().WithMany(d => d.Donations).ForeignKey(k => k.DonatedBy_PersonId);

I get the error described when I try to retrieve data using an include: IQueryable dbQuery = context.Set().AsNoTracking(); dbQuery = dbQuery.Include<T, object>(navigationProperty);

where T is Donation and I am trying to include DonatedBy.

Maybe I've just not got the ModelBuilder syntax right?

I am using 7.0.0-rc1-15886.

ChangedHourly commented 9 years ago

Posted just too soon - I think it was just my Syntax for ModelBuilder. I updated configuration as below and all seems OK:

        modelBuilder.Entity<Donation>().HasOne<Donor>(d => d.DonatedBy).WithMany(d => d.Donations).ForeignKey(k => k.DonatedBy_PersonId);
maumar commented 9 years ago

The new syntax is correct.