2012-02-24 47 views
0

我有一個表Customers鏈接到另一個表Addresses。 Addresses表具有由{CustomerID,LanguageID}組成的主鍵。使用LINQ和EF 4.1填充字典<S,T>與相關實體數據的屬性

我想wrtie LINQ查詢,我實例化一個類型,並在地址表中的地址填充它的

Dictionary<string, Address> Addresses {get;set;}

財產。每個Langauge都將成爲字典中的關鍵。

像這樣:

from c in customers 
from a in c.Addresses 
select new DataContainer 
{ 
    ID = c.CustomerId, 
    ... 
    Addresses.Add(a.LanguageId, a), 
    ... 
}; 

我知道,我真的做不到在對象初始化的。新增()調用,但有什麼辦法,使這項工作?

注意:我當然可以像往常一樣創建類型,然後返回並顯式填充Addresses屬性。

+0

難道你沒有比語言更多的地址嗎?或者它是每個客戶的詞典? – 2012-02-24 08:35:37

+0

@亨克:每個客戶有7個地址。所以每個客戶都有一個獨裁者。 – John 2012-02-24 08:41:04

回答

1

我沒有記憶記得,如果下面的代碼編譯,但你可以嘗試這樣的事:

from c in customers 
from a in c.Addresses 
select new DataContainer 
{  
    Addresses = new Dictionary<string, Address> {{a.LanguageId, a}}; 
}; 

或者你可以嘗試以下解決方案: Instantiating a Dictionary from a LINQ projection

+0

+1 - 這應該做的伎倆(特別是如果指的是你的鏈接) – 2012-02-24 08:38:48

+0

我不明白這將如何工作,因爲每個客戶有一個DataContainer,每個容器需要有7個地址(來自地址表) 。創建一個像上面這樣的新字典總是隻會向字典中添加一個條目。對? – John 2012-02-24 09:24:43

+0

似乎對象初始值設定項僅支持單個項目,即不支持字典。我得到一個異常。 – John 2012-02-24 10:02:54

1

一種安全的方式做這是像這樣:

如果DataContainer看起來是這樣的:

public class DataContainer 
{ 
    public string ID { get; set; } 
    public Address Address { get; set; } 
} 

你可以這樣做:

from c in customers 
from a in c.Addresses 
select new DataContainer 
{ 
    ID = c.CustomerId, 
    Address = a 
}; 
var dic = new Dictionary<string, Address>(); 

foreach (var n in query) 
{ 
    dic.Add(ID,a); 
} 

或簡稱做到這一點:

var dic = query.ToDictionary<DataContainer, string, Address>(n => n.ID, n => n.a); 
+0

謝謝你,但最後一行代碼有錯誤,它應該是: var dic = query.ToDictionary (n => n.ID,n => n.a); – GrandMasterFlush 2012-12-14 15:26:20

+0

我編輯它,謝謝。 – 2012-12-14 20:19:19

0

在響應對亨克約翰的評論。

我寫了一個字典擴展

public static Dictionary<T, K> Build<T, K>(this Dictionary<T, K> dictionary, T key, K value) 
{ 
     dictionary[key] = value; 
     return dictionary; 
} 

現在你可以做這樣的事情:

from c in customers 
from a in c.Addresses 
select new DataContainer 
{  
    Addresses = new Dictionary<string, Address>() 
               .Build(a.LanguageId, a) 
}; 

對我來說,它的工作。 :)