mad moe
mad moe

Reputation: 322

Storing Entity Framework Objects in Dictionary

I can't seem to load an "entity" into a dictionary. I get a "Object reference not set to an instance of an object" when trying to add anything to the dictionary. Any help is greatly appreciated.

private TranslationEntities _db = new TranslationEntities();

private Dictionary<int, Language> _data;


private void LoadData()
        {
             var languages = _db.Languages.Include("Region").OrderBy(e => e.Region.Name).ThenBy(e => e.Name);

             foreach (Language item in languages)
              {
                   _data.Add(item.Id, item);   //// ERRORS HERE ////
              }
        }

Upvotes: 0

Views: 1266

Answers (1)

Shyju
Shyju

Reputation: 218882

Initialize your dictionary before invoking any functions on that.

private void LoadData()
{
    _data = new Dictionary<int, Language>();
    var languages = _db.Languages.Include("Region").OrderBy(e => e.Region.Name).ThenBy(e => e.Name);

    foreach (Language item in languages)
    {
        _data.Add(item.Id, item);   //// ERRORS HERE ////
    }
}

Here i initialized inside the method. You may consider initializing the dictionary in your class constructor as well depending on your scenario/code.

Upvotes: 4

Related Questions