How to make a Linq query with ToDictionary correctly()

There are a couple of requests:

string image = product.ProductCharacteristics
           .Where(c => c.Characteristic.Name == "Image")
           .Select(c => c.Characteristic.Value)
           .FirstOrDefault();

string price = product.ProductCharacteristics
           .Where(c => c.Characteristic.Name == "Price")
           .Select(c => c.Characteristic.Value)
           .FirstOrDefault();

I want to do this with a single query through the dictionary:

public Dictionary<string, string> dict = p.ProductCharacteristics
.ToDictionary(c=> c.Characteristic.Name, c=> c.Characteristic.Value)

But nothing comes out, I get an error. And so I tried:

public Dictionary<string, string> dict = = product.ProductCharacteristics
                .Select(с => new { с.Characteristic.Name, с.Characteristic.Value })
                .AsEnumerable()
                .ToDictionary(с => с.Name, с => с.Value)

Also a mistake:

LINQ to Entities does not recognize the
method 'System.Collections.Generic.Dictionary`2[System.String,System.String]
ToDictionary[<>f__AnonymousType3`2,String,String]
System.Collections.Generic.IEnumerable`1[<>f__AnonymousType3`2
System.String,System.String]], System.Func`2[<>f__AnonymousType3`2
System.String,System.String],System.String], System.Func`2
<>f__AnonymousType3`2[System.String,System.String],System.String])' method,
and this method cannot be translated into a store expression. 

How to build a query correctly?

Author: Nicolas Chabanovsky, 2016-03-19

1 answers

Try this

dict = (product.ProductCharacteristics
              .AsNoTracking()
              .Where(x => x.Characteristic.Name == "Image")
              .ToDictionary(x => x.Name, x => x.Value))
              .ToDictionary(s => s.Key, s => s.Value);
 1
Author: Rulet, 2016-03-21 08:30:36