Is it possible to convert IQueryable <Derived> to IQueryable <Base>?

I know about covariance and I know that in C # this will not be possible until version 4.0.

However, I am interested in knowing a specific case. Is there a way to convert IQueryable<Derived>

to IQueryable<Base>

by creating a wrapper class that doesn't actually execute the request, but can actually "pass" the call .Where<>()

?

My use case is that I'm trying to figure out a database schema that has many similar tables. Most of the fields are generic, and many of the generic fields must be queried on every table. I am using LinqToSql. I was hoping to avoid duplicating all queries for each table.

+2


source to share


2 answers


Is the following what you are looking for?

var results = queryable.OfType<Base>.Where(...);

      



The OfType method will collect whatever is of the specified type, and if all items in the collection are either base or derived from base types, they must match. In the following, where all the elements will be of type Base.

+5


source


The following will work, albeit less pretty:



var results = queryable.Select(derived => (Base)derived).Where(...);

      

0


source







All Articles