Efcore: Query: Inheritance with include navigation property fails when using Cast<T>

Created on 14 Jan 2020  路  6Comments  路  Source: dotnet/efcore

Hello,

I have a base object where I inherit from. In a derived class I have a navigation property.

```C#
public class BaseObject{
public int Id{get;set;}
}

public class Material : BaseObject
{
}

public class ExternalObject : BaseObject
{
public ExternalObjectOptions Option{get;set;}
}

public class ExternalObjectOptions
{
public int Id{get;set;}
public int ObjectId{get;set;}
public ExernalObject Object{get;set;}
}


With following mapping.
```C#
Map(EntityTypeBuilder<BaseObject> builder)
{
  builder.ToTable("BaseObjects").HasKey(p=>p.Id);
}

```C#
Map(EntityTybeBuilder builder)
{
builder.HasOne(p=>p.Option).WithOne(p=>p.Object).HasForeignKey(p=>p.ObjectId);
}

```C#
Map(EntityTybeBuilder<ExternalObjectOptions> builder)
{
  builder.ToTable("ExternalObjectOptions").HasKey(p=>p.Id);
  builder.HasOne(p=>p.Object).WithOne(p=>p.Option).HasForeignKey<ExternalObjectOptions>(p=>p.ObjectId);
}

In ef core 1.1 I had following way to get a ExternalObject:

```C#
ExternalObject obj = query.AsNotTracking().Cast().Include(p=>p.Option).First(predicate);


Now I have made a upgrade to efcore 3.1 but getting following error now: "Value cannot be null. (Parameter 'key')"

If I change the retrieving of data to this:
```C#
ExternalObject obj = query.AsNotTracking().Cast<ExternalObject>().First(predicate);

objects are returned.

Some ideas what I have done wrong?

EF Core version: 3.1
Database provider: Pomelo.EntityFrameworkCore.MySql 3.1
Target framework: .NETCore 3.1
Operating system: Windows 10
IDE: Visual Studio 2019

area-in-memory area-query customer-reported punted-for-5.0 type-bug

All 6 comments

@maumar Thoughts on this? Looks like the issue is Include after a Cast.

Yup, it's a bug.

@ReginaldBull try the following workaround:

ExternalObject obj = query.AsNotTracking().OfType<ExternalObject>().Include(p=>p.Option).First(predicate);

This works, at least on SqlServer.

Thanks. I will try your workaround.

I tried today your proposed workaround. It's also working for MariaDb with the Pomelo connector.

@maumar - Can I poach this?

this now works on relational but fails on InMemory

Was this page helpful?
0 / 5 - 0 ratings