在Dictionary中存储实体框架对象

时间:2012-07-15 04:50:02

标签: c# entity-framework dictionary

我似乎无法将“实体”加载到字典中。在尝试向字典添加任何内容时,我得到“对象引用未设置为对象的实例”。非常感谢任何帮助。

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 ////
              }
        }

1 个答案:

答案 0 :(得分:4)

在调用任何函数之前初始化dictionary

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 ////
    }
}

我在这里初始化了方法。您可以考虑在类constructor中初始化字典,具体取决于您的方案/代码。