why does DbContext.Set<TEntity> return DbSet instead of IDbSet?

Topics: EF Runtime
Dec 29, 2012 at 1:47 PM

Why does DbContext.Set<TEntity> returns DbSet instead of IDbSet? Is it possible to change this for EF6?

Developer
Dec 31, 2012 at 9:57 PM

The reason is that Set always returns a DbSet and it is very common that people want to use it specifically as a DbSet. If it returned an IDbSet then it would require a cast to assign it to a DbSet property, etc. On the other hand, it doesn't require a cast to assign a DbSet to an IDbSet. It's the same reason that other members in the BCL do the same thing--for example ToList returns a List and not an IList.

It would break a lot of applications if we changed this so it is very unlikely that we will do so for EF6 or any future release.

If you want it to return an IDbSet for fakes/mocks, I think that is a reasonable request, but the usual pattern we recommend for creating fakes doesn't require it. This post by Rowan contains the details: http://romiller.com/2012/02/14/testing-with-a-fake-dbcontext/

Thanks,
Arthur