DbSet<T>
CANNOT be co-variant. Firstly, this is because in C#, classes cannot be co-variant...only interfaces. Secondly because DbSet<T>
has both co-variant and contra-variant methods.
Take the following two examples.
DbSet<CategoryType> set = context.Set<CategoryType>();
IQueryable<IItemType> query = set.Where(x => x.Foo == Bar);
So we know for a fact that all CategoryType
s are IItemType
, so we know this can always work.
However conversely try this...
DbSet<CategoryType> set = context.Set<CategoryType>();
IItemType newItemType = new ProductType();
set.Add(newItemType); // Compiler error.
Not all IItemType
s are CategoryType
. So if we could cast DbSet<CategoryType>
to DbSet<IItemType>
we would get run time errors when adding... Since the compiler knows that this might not always work, it won't let you do the casting.
However there are interfaces that DbSet<T>
does allow Co-Variance on. You can try casting it to IQueryable<IItemType>
for example.
However it sounds like you are trying to query against the DbSet using a query against the interface... try the following
DbSet<CategoryType> set = context.Set<CategoryType>();
IQueryable<IItemType> cast = set.OfType<IITemType>(); //(or .Cast<>() works too)
IQueryable<IItemType> query = cast.Where(x => x ....);