[英]How to query an Entity Framework entities container for objects of derived entity classes?
我的數據模型中有一個復雜的繼承結構。 我的模型中的大多數類(在VS 2010中設計,之后由其生成的DB)來自3個基本類。 在上下文成員中只能找到這3個類。 我如何使用所有派生類?
羅傑的答案有點作品,但可能不會給你想要的結果。 使用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>();
同樣,Roger的第二個查詢可以重寫為:
var horses = from horse in ctx.AnimalSet.OfType<Horse>()
where horse.TracksWon > 3
select horse;
哪個更容易閱讀,但將結果類型更改為IQueryable<Horse>
。
您可以像這樣查詢子類型:
var horses = from animal in ctx.AnimalSet
where animal is Horse
select animal as Horse;
這將從我的考試上下文中的Animal集中獲取所有Horse對象。
如果您希望查詢子類型特定屬性,您可以執行以下操作:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.