Is calling AsQueryable on a DbSet "safe"?

.net c# entity-framework-6

Question

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?

1
5
1/4/2013 6:48:10 PM

Accepted Answer

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.

7
1/4/2013 1:34:59 PM

Popular Answer

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(...)...



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow