简体   繁体   中英

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 . 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.

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

A safe way to do this is like so:

If DataContainer looks like this:

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. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM