2010-05-08 59 views

回答

6

您可以查询这样的亚型:

var horses = from animal in ctx.AnimalSet 
       where animal is Horse 
       select animal as Horse; 

这将获取所有马从我examle上下文中的动物组对象。

如果您希望在子类型特定的属性查询,你可以这样做:

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; 

这都将转换为SQL,所以不存在像获取所有的动物和筛选在客户端上的开销,它的工作原理正如它应该。

HTH

10

罗杰的回答样的作品,但可能不会给你你想要的结果。通常使用OfType()更好。用他的例子:

var horses = from animal in ctx.AnimalSet 
      where animal is Horse 
      select animal as Horse; 

这使得IQueryable<Animal>horses。但在这种情况下,你可能想IQueryable<Horse>,你可以得到由:

var horses = from animal in ctx.AnimalSet.OfType<Horse>() 
      select animal; 

...或者只是:

var horses = ctx.AnimalSet.OfType<Horse>(); 

同样,罗杰的第二查询可以被改写为:

var horses = from horse in ctx.AnimalSet.OfType<Horse>() 
      where horse.TracksWon > 3 
      select horse; 

哪一个更容易阅读,但将结果类型更改为IQueryable<Horse>