Skip to content

Query: ThenInclude throw ArgumentNullException when entity implements the interface #3409

Closed
@Boglen

Description

@Boglen
public interface ITestEntity1
{
    int Id { get; set; }

    ICollection<ITestEntity2> EntityChilds { get; set; }
}

public interface ITestEntity2
{
    int Id { get; set; }

    ICollection<ITestEntity2> Childs { get; set; }

    int? TestEntity1Id { get; set; }
    ITestEntity1 ParentRef { get; set; }
    int? TestEntity2Id { get; set; }
    ITestEntity2 Parent { get; set; }
}

public class TestEntity11 : ITestEntity1
{
    public int Id { get; set; }

    public virtual ICollection<ITestEntity2> EntityChilds { get; set; }
}

public class TestEntity22 : ITestEntity2
{
    public int Id { get; set; }

    public virtual ICollection<ITestEntity2> Childs { get; set; }

    public int? TestEntity1Id { get; set; }
    public ITestEntity1 ParentRef { get; set; }
    public int? TestEntity2Id { get; set; }
    public ITestEntity2 Parent { get; set; }
}

public class TestContext22 : DbContext
{
    public DbSet<TestEntity11> Entity1 { get; set; }
    public DbSet<TestEntity22> Entity2 { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

        modelBuilder.Entity<TestEntity11>(b => {
            b.HasKey(k => k.Id);
            b.HasMany(p => (ICollection<TestEntity22>)p.EntityChilds).WithOne(o => (TestEntity11)o.ParentRef).HasForeignKey(k => k.TestEntity1Id).IsRequired(false);
        });

        modelBuilder.Entity<TestEntity22>(b => {
            b.HasKey(k => k.Id);
            b.HasMany(p => (ICollection<TestEntity22>)p.Childs).WithOne(o => (TestEntity22)o.Parent).HasForeignKey(k => k.TestEntity2Id).IsRequired(false);
        });
    }

}

        using (var context = new TestContext22())
        {
            context.Database.EnsureDeleted();
            context.Database.EnsureCreated();

            var ent1 = context.Add(new TestEntity11()).Entity;
            context.SaveChanges();

            var ent21 = context.Add(new TestEntity22()).Entity;
            var ent22 = context.Add(new TestEntity22()).Entity;
            var ent23 = context.Add(new TestEntity22()).Entity;

            context.SaveChanges();

            ent21.ParentRef = ent1;
            ent21.Childs = new List<ITestEntity2>() { ent22, ent23 };


            context.SaveChanges();


            //Throw exception
            var getIt = context.Entity1.Include(p => p.EntityChilds).ThenInclude(i => i.Childs).ToList();
        }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions