Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Problem with LazyLoading and TPH #14039

Closed
Arikael opened this issue Nov 29, 2018 · 1 comment · Fixed by #19409
Closed

Problem with LazyLoading and TPH #14039

Arikael opened this issue Nov 29, 2018 · 1 comment · Fixed by #19409
Labels
closed-fixed The issue has been fixed and is/will be included in the release indicated by the issue milestone. customer-reported punted-for-3.0 type-bug
Milestone

Comments

@Arikael
Copy link

Arikael commented Nov 29, 2018

If you enable lazy loading, use TPH (Base, Entity1, Entity2) and have a navigational property from Entity1 to Entity2 the exception below occurs.

This is further described here
https://stackoverflow.com/questions/4811194/what-is-the-syntax-for-self-referencing-foreign-keys-in-ef-code-first

and can be reproduced here
https://github.com/Arikael/EfTest/tree/master/EfTest

as a workaround you can introduce the foreign key property yourself

public Guid? CompanyId { get; set; }
Exception message:
Unable to cast object of type 'System.DateTime' to type 'System.Nullable`1[System.Guid]'.
Stack trace:
   at lambda_method(Closure , ValueBuffer )
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalMixedEntityEntry..ctor(IStateManager stateManager, IEntityType entityType, Object entity, ValueBuffer& valueBuffer)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntryFactory.NewInternalEntityEntry(IStateManager stateManager, IEntityType entityType, Object entity, ValueBuffer& valueBuffer)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.StartTrackingFromQuery(IEntityType baseEntityType, Object entity, ValueBuffer& valueBuffer, ISet`1 handledForeignKeys)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityTrackingInfo.StartTracking(IStateManager stateManager, Object entity, ValueBuffer& valueBuffer)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryBuffer.StartTracking(Object entity, EntityTrackingInfo entityTrackingInfo)
   at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider._TrackEntities[TOut,TIn](IEnumerable`1 results, QueryContext queryContext, IList`1 entityTrackingInfos, IList`1 entityAccessors)+MoveNext()
   at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
   at System.Collections.Generic.List`1.AddEnumerable(IEnumerable`1 enumerable)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at EfTest.Program.Main(String[] args) in C:\Users\haehadmin\Documents\Projects\EfTest\EfTest\Program.cs:line 16

Steps to reproduce

clone https://github.com/Arikael/EfTest/tree/master/EfTest
change the ConnectionString to your local DB and run the application

Further technical details

EF Core version: 2.1.4.
Database Provider: Microsoft.EntityFrameworkCore.SqlServer
Operating system: Win 10
IDE: Visual Studio 2017 15.3.9

@ajcvickers
Copy link
Member

Repros on 2.1 and 2.2 preview3.
Model:

  EntityType: Base Abstract
    Properties: 
      Id (Guid) Required PK AfterSave:Throw ValueGenerated.OnAdd 0 0 0 -1 0
      Discriminator (no field, string) Shadow Required AfterSave:Throw 1 1 -1 0 -1
    Keys: 
      Id PK
    Annotations: 
      NavigationAccessMode: Field
      Relational:DiscriminatorProperty: Discriminator
      Relational:DiscriminatorValue: Base
      Relational:TableName: Bases
  EntityType: Company Base: Base
    Properties: 
      CompanyName (string) 2 2 -1 -1 -1
    Service properties: 
      LazyLoader (no field, ILazyLoader)
    Annotations: 
      NavigationAccessMode: Field
      Relational:DiscriminatorValue: Company
  EntityType: Person Base: Base
    Properties: 
      Birthday (DateTime) Required 2 2 -1 -1 -1
      CompanyId (no field, Nullable<Guid>) Shadow FK Index 3 3 1 1 1
    Navigations: 
      Company (<Company>k__BackingField, Company) ToPrincipal Company PropertyAccessMode.Field 0 -1 2 -1 -1
        Annotations: 
          PropertyAccessMode: Field
    Service properties: 
      LazyLoader (no field, ILazyLoader)
    Foreign keys: 
      Person {'CompanyId'} -> Company {'Id'} ToPrincipal: Company
    Annotations: 
      NavigationAccessMode: Field
      Relational:DiscriminatorValue: Person

Minimal repro:

using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;

public abstract class Base
{
    public Guid Id { get; set; }
}

public class Company : Base
{
    public string CompanyName { set; get; }
}

public class Person : Base
{
    public DateTime Birthday { set; get; }

    public virtual Company Company { set; get; }
}

public class BloggingContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseLazyLoadingProxies()
            .UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Test;ConnectRetryCount=0");

    public DbSet<Person> Persons { set; get; }
    public DbSet<Company> Companies { set; get; }
    public DbSet<Base> Bases { set; get; }


public class Program
{
    public static void Main()
    {
        using (var context = new BloggingContext())
        {
            context.Database.EnsureDeleted();
            context.Database.EnsureCreated();

            context.Add(new Person());
            context.SaveChanges();
        }

        using (var context = new BloggingContext())
        {
            var test = context.Bases.ToList();
        }
   }
}

@ajcvickers ajcvickers self-assigned this Dec 3, 2018
@ajcvickers ajcvickers added this to the 3.0.0 milestone Dec 3, 2018
@ajcvickers ajcvickers modified the milestones: 3.0.0, Backlog Jun 28, 2019
@ajcvickers ajcvickers modified the milestones: Backlog, 5.0.0 Nov 13, 2019
ajcvickers added a commit that referenced this issue Dec 26, 2019
Fixes #14039

Issue was fixed as part of 3.0/3.1 changes.
@ajcvickers ajcvickers modified the milestones: 5.0.0, 3.1.0 Dec 26, 2019
@ajcvickers ajcvickers added the closed-fixed The issue has been fixed and is/will be included in the release indicated by the issue milestone. label Dec 26, 2019
ajcvickers added a commit that referenced this issue Dec 30, 2019
Fixes #14039

Issue was fixed as part of 3.0/3.1 changes.
@ajcvickers ajcvickers removed their assignment Sep 1, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
closed-fixed The issue has been fixed and is/will be included in the release indicated by the issue milestone. customer-reported punted-for-3.0 type-bug
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants