I am using EF Core 6, and my DbContext looks like this :
public class SpaceBattlesDatabase: DbContext, ISpaceBattlesDataBase
{
public DbSet<Building> Buildings => Set<Building>();
// + other irrelevant code
}
I would like to abstract it with an interface, to use in the central layer in a clean architecture..
public interface ISpaceBattlesDataBase
{
public IQueryable<Building> Buildings { get; }
}
But the compilator warns me :
Error CS0738 'SpaceBattlesDatabase' does not implement interface member 'ISpaceBattlesDataBase.Buildings'. 'SpaceBattlesDatabase.Buildings' cannot implement 'ISpaceBattlesDataBase.Buildings' because it does not have the matching return type of 'IQueryable'.
But according to the documentation and the metadata, DbSet<TEntity> should implement IQueryable<TEntity>..
IEnumerable<T> doesn't work either..
Am I missing something here ?
How can I abstract the DbSet to use in the interface ?
Thank you
C# does not support return type covariance for interface implementations (I would say that explanation given by Eric Lippert here can shed some light on why). In this particular case you can work around with explicit interface implementation:
Another approach with abstract base class inheriting from interface due to C# 9 feature covariant returns types: