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()?
It should actually be:
Remember, you’re trying to cast the
PERSONto aTEACHER, so it goes inside the delegate. The result ofSchool.Select(x => x.PERSON)by itself is actually anIEnumerable<PERSON>, which is not convertible toIEnumerable<TEACHER>.One more thing – if some
PERSONinstances are not actuallyTEACHERs (i.e. they areSTUDENTs instead), you’re going to end up withnullreferences in the output. IfPERSONcan be more than one type, you would probably want to write it out like this instead:This will actually filter out all of the
PERSONentities that aren’tTEACHERs, so you only get backTEACHERinstances in the sequence (no nulls).Also note that the
from x in ysyntax is the “query” (specifically query comprehension syntax). The second form is lambda syntax.