Design of abstract generic DbContext class in EF Core

c# entity-framework entity-framework-core generics

Question

I'm having trouble implementing an abstract generic base class, using EF Core. It's probably something obvious, but I'm not seeing it.

base class:

public abstract class AContext<TUser> : IdentityDbContext<TUser> 
  where TUser : IdentityUser {

    public AContext(DbContextOptions<AContext<TUser>> options, ILogger<AContext<TUser>> logger) 
      : base(options) {
    }

}

subclass:

public class Context : AContext<User> {

    public Context(DbContextOptions<Context> options, ILogger<Context> logger)
      : base(options, logger) {   // problem is here with "options"
    }

}

Error: Cannot convert from 'DbContextOptions<Context>' to 'DbContextOptions<AContext<User>>'.

I tried casting but that doesn't work. Is the problem due to it not being covariant? Can I redesign it somehow?

1
1
1/5/2017 11:22:22 AM

Accepted Answer

A DbContextOptions<Context> is not assignable to DbContextOptions<AContext<TUser>>. The reason is that there could be internal write operations to objects of type T, which for DbContextOptions<Context> would be Context. DbContextOptions<AContext<TUser>> can not provide that, because it's T is an AContext<TUser>.

Covariance is not an answer for you, since co- and contravariance is only available for interfaces, not for classes.

If you change the parameter type in your constructor from DbContextOptions<Context> to DbContextOptions<AContext<User>>, everything should work fine.

3
1/5/2017 11:41:34 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow