tags:

views:

77

answers:

1

I'm trying to rewrite a LINQ To Entities query to an expression. My model is a School which can have many Persons. Persons are inherited out to teachers, students, etc.

The following query works for me:

IQueryable<DAL.TEACHER> teacher = 
from p in School 
select p.PERSON as ESBDAL.TEACHER;

How would I write this as a query expression? I thought something like:

IQueryable<DAL.TEACHER> teacher = 
School.Select(x=>x.PERSON) as IQueryable<DAL.TEACHER>;

Unfortunately this statement doesn't work. Am I misunderstanding the .Select()?

+7  A: 

It should actually be:

School.Select(x => x.PERSON as DAL.TEACHER)

Remember, you're trying to cast the PERSON to a TEACHER, so it goes inside the delegate. The result of School.Select(x => x.PERSON) by itself is actually an IEnumerable<PERSON>, which is not convertible to IEnumerable<TEACHER>.

One more thing - if some PERSON instances are not actually TEACHERs (i.e. they are STUDENTs instead), you're going to end up with null references in the output. If PERSON can be more than one type, you would probably want to write it out like this instead:

School.Select(x => x.PERSON).OfType<DAL.TEACHER>();

This will actually filter out all of the PERSON entities that aren't TEACHERs, so you only get back TEACHER instances in the sequence (no nulls).

Also note that the from x in y syntax is the "query" (specifically query comprehension syntax). The second form is lambda syntax.

Aaronaught
Great answer, thanks alot!
itchi