使用 LINQ 和 EF 4.1 填充字典具有相关实体数据的属性
我有一个表Customers
,它链接到另一个表Addresses
。 地址表的主键由 {CustomerID, LanguageID} 组成。
我想编写一个 LINQ 查询,在其中实例化一个类型并填充其
Dictionary
属性与地址表中的地址。每种语言都将成为字典中的关键。
就像这样:
from c in customers
from a in c.Addresses
select new DataContainer
{
ID = c.CustomerId,
...
Addresses.Add(a.LanguageId, a),
...
};
我知道我确实无法在对象初始值设定项中执行 .Add() 调用,但是有没有办法使其工作?
注意:我当然可以像往常一样创建类型,然后返回并显式填充 Addresses 属性。
I have a table Customers
that is linked to another table Addresses
.
The Addresses table has a Primary Key made up of {CustomerID, LanguageID}.
I would like to wrtie a LINQ query where I instantiate a type and populate its
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?
Note: I could of course create the type as usual and then go back in and populate the Addresses property explicitely.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不记得以下代码是否可以编译,但您可以尝试这样的事情:
或者您可以尝试以下解决方案:
从LINQ 投影
I don't remember from memory if following code will compile, but you can try something like this:
Or you can try following solution:
Instantiating a Dictionary from a LINQ projection
一种安全的方法是这样的:
如果
DataContainer
看起来像这样:您可以这样做:
或者简单地说,这样做:
A safe way to do this is like so:
If
DataContainer
looks like this:You can do this:
Or for short do this:
回应约翰对亨克的评论。
我写了一个字典扩展
现在你可以做这样的事情:
对我来说它确实有效。 :)
In response to John's comment for henk.
I wrote a Dictionary extension
Now you can do something like this:
For me it does work. :)