2010-08-19 38 views
1

如果我有從基礎實體繼承的實體(比如說「小工具」,「小工具」和「小工具」從「設備」繼承),我想查詢設備並返回每個項目中產生的投影的具體類型,就像這樣:Linq2EF在查詢投影中返回子類的類型

from d in Devices 
select new 
{ 
    Name = d.Name, 
    Type = d.GetType() 
}; 

這將返回類似的列表:

Spring, Widget 
Gear, Gizmo 
Tape, Gadget 
Scissors, Gizmo 
Screw, Widget 

當然,EF抱怨,因爲的GetType()是不是SQL Server cannonical功能。有沒有辦法做到這一點?

回答

1

有兩種方法。如果只涉及幾種類型,你可以這樣做:

from d in Devices 
let typeName = d is Spring ? "spring" : d is Widget ? "widget" : "etc." 
select new 
{ 
    Name = d.Name, 
    Type = typeName 
}; 

醜陋,但在案件中必要。

或者,進入L2O:

(from d in Devices 
select new 
{ 
    Name = d.Name, 
    Obj = o 
}).AsEnumerable() 
    .Select(
    d => new 
      { 
       Name = d.Name, 
       Type = d.GetType() 
      }); 
+0

第一種方法工作得很好,因爲我有已知類型的數量有限,不想列舉的數據。 – CodeGrue 2010-08-20 13:56:46