Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to cast each item in a LINQ to Entities query to an interface?

I have an entity object 'User' which implements 'IUser':

IQueryable<User> users = Db.User;
return users;

But what I actually want to return is:

IQueryable<IUser>

So what is the best way to convert

IQueryable<User>

to

IQueryable<IUser>

without actually running the query? Right now I am doing this but it seems like a hack:

IQueryable<IUser> users = Db.User.Select<User, IUser>(u => u);
like image 1000
Mike Comstock Avatar asked Aug 06 '09 16:08

Mike Comstock


People also ask

How cast the LINQ query in the C#?

LINQ Cast() Method In LINQ, Cast operator is used to cast/convert all the elements present in a collection into a specified data type of new collection. In case if we try to cast/convert different types of elements (string/integer) in the collection, then the conversion will fail, and it will throw an exception.

What does the .include method do in LINQ?

Introduction to LINQ Include. LINQ include helps out to include the related entities which loaded from the database. It allows retrieving the similar entities to be read from database in a same query. LINQ Include() which point towards similar entities must read from the database to get in a single query.

What is the data type for LINQ query?

There is no single datatype for LINQ queries as it depends on the context. In your case you are selecting "Car" so the datatype is going to be IQueryable. As pointed out in the comments you can hold your mouse over any var (not just those involving LINQ queries) to get the datatype.

What is LINQ to objects in C#?

The term "LINQ to Objects" refers to the use of LINQ queries with any IEnumerable or IEnumerable<T> collection directly, without the use of an intermediate LINQ provider or API such as LINQ to SQL or LINQ to XML. You can use LINQ to query any enumerable collections such as List<T>, Array, or Dictionary<TKey,TValue>.


1 Answers

Your "hacky" solution looks fine to me.

like image 127
Craig Stuntz Avatar answered Sep 28 '22 20:09

Craig Stuntz