Reputation: 9265
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?
Upvotes: 2
Views: 1141
Reputation: 14007
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.
Upvotes: 3