2010-01-26 74 views
2

我對LINQ以及一般現代數據驅動的應用程序設計技術很感興趣,所以這可能是一個非常基本的問題。LINQ投影演示模型

我想創建一個投影的幾個不同的實體框架實體到一個簡單的演示模型。假設我有父項(屬性是ID,名稱,年齡)和子項(屬性是ID,名稱,年齡,帶有對父項的引用)。我想將它們投影到PresentationParent和PresentationChild,其中所有屬性都相同,但PresentationParent有一個List。我如何在LINQ中做到這一點?

from p in entities.Parent 
select new PresentationParent 
{ 
    ID = p.ID, 
    Name = p.Name, 
    Age = p.Age, 
    Children = [[?? What goes here ??]] 
} 

這是否正確?我似乎只能找到簡單的平面投影的例子。

回答

4

事情是這樣的:

from p in entities.Parent 
select new PresentationParent { 
    ID = p.ID, 
    Name = p.Name, 
    Age = p.Age, 
    Children = (from c in entities.Child 
       where c.Parent == p 
       select new PresentationChild { 
        ID = c.ID, 
        Name = c.Name, 
        Age = c.Age 
       }).ToList() 
} 

然而,你的實體應該來預配置已經是必要的外鍵關係,所以你可以做這樣的事情:

from p in entities.Parent 
select new PresentationParent { 
    ID = p.ID, 
    Name = p.Name, 
    Age = p.Age, 
    Children = p.Children.ToList() 
} 

當然,這將返回每個孩子的所有屬性,因此您可能想要投射孩子:

from p in entities.Parent 
select new PresentationParent { 
    ID = p.ID, 
    Name = p.Name, 
    Age = p.Age, 
    Children = (from c in p.Children 
       select new PresentationChild { 
        ID = c.ID, 
        Name = c.Name, 
        Age = c.Age 
       }).ToList() 
} 
+0

這編譯,但是當您試圖枚舉結果集失敗 - 它抱怨說,LINQ到實體「不承認」 ToList方法,並且「此方法不能轉換爲商店表達式」。它工作,如果我使用LINQ到SQL而不是EF雖然。 – nlawalker 2010-01-26 22:27:14

+0

我現在無法自己嘗試這種方式,但是您可以嘗試移動「ToList」方法來代替整個外部查詢。這應該使L2E提供者能夠更靈活地將查詢轉換爲有效的SQL。 – 2010-01-27 08:37:44

0

另一種選擇,如果關係不成立,足有可用的訪問:

from p in entities.Parent 
from c in entities.Children on p.ID equals c.parentID into children 
select new PresentationParent 
{ 
    ID = p.ID, 
    Name = p.Name, 
    Age = p.Age, 
    Children = children.ToList() 
} 
+0

不會children.ToList()創建一個Child對象列表,而不是PresentationChild對象? – nlawalker 2010-01-26 22:14:11