[英]Using LINQ and EF 4.1 to populate a Dictionary<S,T> Property with related entity data
I have a table Customers
that is linked to another table Addresses
. 我有一个链接到另一个表
Addresses
Customers
表。 The Addresses table has a Primary Key made up of {CustomerID, LanguageID}. 地址表的主键由{CustomerID,LanguageID}组成。
I would like to wrtie a LINQ query where I instantiate a type and populate its 我想写一个LINQ查询,我实例化一个类型并填充它
Dictionary<string, Address> Addresses {get;set;}
property with the addresses in the Address table. 属性和地址表中的地址。 Each Langauge is to become the key in the dictionary.
每个语言版本都将成为词典中的键。
Like so: 像这样:
from c in customers
from a in c.Addresses
select new DataContainer
{
ID = c.CustomerId,
...
Addresses.Add(a.LanguageId, a),
...
};
I know that I really can't do the .Add() call in an object initializer, but is there a way to make that work? 我知道我真的不能在对象初始化程序中进行.Add()调用,但是有没有办法使它起作用?
Note: I could of course create the type as usual and then go back in and populate the Addresses property explicitely. 注意:我当然可以像往常一样创建类型,然后返回并显式填充Addresses属性。
I don't remember from memory if following code will compile, but you can try something like this: 我不记得有没有下面的代码可以编译,但是您可以尝试执行以下操作:
from c in customers
from a in c.Addresses
select new DataContainer
{
Addresses = new Dictionary<string, Address> {{a.LanguageId, a}};
};
Or you can try following solution: Instantiating a Dictionary from a LINQ projection 或者,您可以尝试以下解决方案: 从LINQ投影实例化字典
A safe way to do this is like so: 一个安全的方法是这样的:
If DataContainer
looks like this: 如果
DataContainer
看起来像这样:
public class DataContainer
{
public string ID { get; set; }
public Address Address { get; set; }
}
You can do this: 你可以这样做:
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);
}
Or for short do this: 或简短地说:
var dic = query.ToDictionary<DataContainer, string, Address>(n => n.ID, n => n.a);
In response to John's comment for henk. 为了回应约翰对汉克的评论。
I wrote a Dictionary extension 我写了字典扩展
public static Dictionary<T, K> Build<T, K>(this Dictionary<T, K> dictionary, T key, K value)
{
dictionary[key] = value;
return dictionary;
}
Now you can do something like this: 现在您可以执行以下操作:
from c in customers
from a in c.Addresses
select new DataContainer
{
Addresses = new Dictionary<string, Address>()
.Build(a.LanguageId, a)
};
For me it does work. 对我来说,它确实有效。 :)
:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.