Say I want to unit test Entity Framework's query logic, one way would be to convert the DbSet<T>
to IQueryable<T>
before building the expression trees for easy mocking. Is this "safe" and is there anything to be aware about?
It is not only safe, it is legal and fully standard. This is what OO is all about. You just downcast. A DbSet
HAS to be a IQUeryable
, per the contract defined by the designers.
Be careful with AsQueryable()
. If one of your variable is of type IQueryable<IEntity>
after calling AsQueryable()
, you don't know anymore what the concrete type of the variable is (DbSet<IEntity>
in your example).
While it's perfectly valid from an OOP perspective (that's the whole point of the interfaces !), it can lead to a lot of bugs/mistakes. Remember that until you enumerate a DbSet<IEntity>
source, you don't actually execute the query.
That's why for example you can't join an in-memory IQueryable<IEntity>
(for example new List<IEntity>{ ... }.AsQueryable()
) with the result of a DbSet<IEntity>
using .Union(...)
...