3

I'm using EF Core 3.0 with .NET Core 3.0. I have an abstract database model that is inherited by 2 classes. Each one has its own table

So we have Class A as the abstract, and class B and C are inheriting A. B and C have separate tables in the database. they are identical and add no extra fields.

Now here is the problem.

if I try to get a list of Bs from the database as following:

List<A> list = await context.Bs.ToListAsync();

this works perfectly fine, the following also works:

A a = context.Bs.FirstOrDefault();

However, the following cause an exception:

A a = await context.Bs.FirstOrDefaultAsync();

This is the exception:

System.ArgumentException: Expression of type 'System.Threading.Tasks.Task`1[B]' cannot be used for return type 'System.Threading.Tasks.Task`1[A]'

I think this is due to the fact that IList is defined to be covariant while System.Task isn't

so, is there a way to workaround this? as far as I know EF core supports inheritance just fine, so how is it supposed to be used if this was wrong?

EDIT:

I didn't mention an important aspect to complicated the problem even more.

in the provided examples above I used context.Bs directly, this simplifies the problem since I know I'm using B.

However in my case I have something called IUserManager, the user manager will resolve the DbSet dynamically, so it will be something like this:

IUserManager manager = GetDynamicVersion();
A a = await manager.UsersTable.FirstOrDefaultAsync();

In this scenario, manager.UsersTable will return IQueryable<A>

Hassan Khallouf
  • 1,170
  • 1
  • 13
  • 30

0 Answers0