Entity Framework to use dictionary object

Viewed 181

In Entity Framework, I want to see if I can fill a dictionary vs one of the model. In the past I have always map to model object. But I wanted to use a dictionary object to avoid ambiguous because multiple CLR types errors.

var dictionaryFlatFee = new Dictionary<int, decimal?>();
var listOfFees = (from p in db.Pricings
                  select new dictionaryFlatFee
                         {
                              p.Id,
                              p.Price,
                         }).AsEnumerable()
                           .ToList();
2 Answers

Just to finalize the answer due to some of the comments to make it clearer. All you need to do is to retrieve db.Pricings and call ToDictionary() method which is part of the Enumerable API:

var FeesDictionary = db.Pricings.ToDictionary(key=>key.Id, val=>val.Price);

db.Pricings returns a DbSet<Pricing> which implements IEnumerable<Pricing> so it makes all Enumerable methods available to manage the returned entities. You could still Select() prior to casting the return as Dictionary<int, decimal?> but it's very unnecessary, so just omit it.

I would also like to refer you to this Site and will tremendously improve your knowledge on LINQ.

You can select data that you need and put in dictionaryFlatFee dictionary by ForEach like this

var dictionaryFlatFee = new Dictionary<int, decimal?>();
(from p in db.Pricings
    select new 
    {
        p.Id,
        p.Price,
    })
    .ToList().ForEach(a => dictionaryFlatFee.Add(a.Id, a.Price));

Another option is ToDictionary method

var dictionary = db.Pricings.ToDictionary(a => a.Id, a => a.Price);
Related