I have a complex inheritance structure in my data model. A majority of classes in my model (which is designed in VS 2010 with a DB generated by it after) are derived from 3 basic classes. And only these 3 classes can be found among the context members. How do I use all the derived classes at all?
views:
203answers:
2
+3
A:
You can query for subtypes like this:
var horses = from animal in ctx.AnimalSet
where animal is Horse
select animal as Horse;
This will fetch all Horse objects from the Animal set in my examle context.
If you wish to query on sub type specific properties you can do:
var horses = from animal in ctx.AnimalSet
where animal is Horse //edit, this line is not needed
let horse = animal as Horse
where horse.TracksWon > 3
select horse;
This will all be translated to SQL, so there is no overhead like fetching all animals and filtering on client side, it works as it should.
HTH
Roger Alsing
2010-05-08 07:32:39
A:
Roger's answer kind of works, but might not give you the results you want. It's generally better to use OfType()
. To use his examples:
var horses = from animal in ctx.AnimalSet
where animal is Horse
select animal as Horse;
This makes horses
of type IQueryable<Animal>
. But in this case you probably want IQueryable<Horse>
, which you can get by:
var horses = from animal in ctx.AnimalSet.OfType<Horse>()
select animal;
... or just:
var horses = ctx.AnimalSet.OfType<Horse>();
Similarly, Roger's second query can be rewritten as:
var horses = from horse in ctx.AnimalSet.OfType<Horse>()
where horse.TracksWon > 3
select horse;
Which is easier to read, but changes the result type to IQueryable<Horse>
.
Craig Stuntz
2010-05-11 17:26:05