簡體   English   中英

使用LINQ和EF 4.1填充字典 <S,T> 具有相關實體數據的屬性

[英]Using LINQ and EF 4.1 to populate a Dictionary<S,T> Property with related entity data

我有一個鏈接到另一個表Addresses Customers表。 地址表的主鍵由{CustomerID,LanguageID}組成。

我想寫一個LINQ查詢,我實例化一個類型並填充它

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

屬性和地址表中的地址。 每個語言版本都將成為詞典中的鍵。

像這樣:

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

我知道我真的不能在對象初始化程序中進行.Add()調用,但是有沒有辦法使它起作用?

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

我不記得有沒有下面的代碼可以編譯,但是您可以嘗試執行以下操作:

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

或者,您可以嘗試以下解決方案: 從LINQ投影實例化字典

一個安全的方法是這樣的:

如果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);

為了回應約翰對漢克的評論。

我寫了字典擴展

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)
};

對我來說,它確實有效。 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM