开发者

Foreign key object not getting filled in EF4

I would think this is very basic stuff, but I'm just not g开发者_JS百科etting it to work.

I try to get a list of objects using lambda expressions like this :

 List<LocalizationGlobalText> list = _entities.LocalizationGlobalTexts.Where(l => l.Language.Id == _currentlanguage).ToList<LocalizationGlobalText>();

The list is fetched, but the foreign key objects are all null. I also tried using LINQ to entities but this results in the same problem :

        IEnumerable<LocalizationGlobalText> bla = (from lgt in _entities.LocalizationGlobalTexts
                                                   join lg in _entities.LocalizationGlobals on lgt.IdLocalizationGlobal equals lg.Id
                                                   where lgt.IdLanguage == _currentlanguage
                                                   select lgt);


By default, Entity Framework only brings in the collection that you specify, without any foreign objects. If you have lazy loading enabled, accessing the foreign properties will cause them to be lazily initialized. If not, you'll need to tell entity framework to eagerly load the properties you want with the first batch.

There are two ways to do this. The first is the "official" way, but I don't like it because it uses magic strings:

var list = _entities.LocalizationGlobalTexts.Include("ForeignProp")
              .Where(l => l.Language.Id == _currentlanguage)
              .ToList<LocalizationGlobalText>();

(Replace "ForeignProp" with the name of the property you want it to eagerly load)

The second way is to set up your selector so that it will be forced to pull this extra data in:

var list = _entities.LocalizationGlobalTexts
              .Where(l => l.Language.Id == _currentlanguage)
              .Select(l => new {l, l.ForeignProp})
              .ToList();

foreach(var item in list)
{
    Console.WriteLine(item.l.Name + item.ForeignProp.Title);
}

Since Entity Framework is smart enough to have made the appropriate connections, you could throw on one more selector and avoid using the anonymous type afterward:

var list = _entities.LocalizationGlobalTexts
              .Where(l => l.Language.Id == _currentlanguage)
              .Select(l => new {l, l.ForeignProp})
              .AsEnumerable() // tells EF to load now. The rest is LINQ to Objects
              .Select(i => i.l)
              .ToList();

foreach(var localization in list)
{
    Console.WriteLine(localization.Name + localization.ForeignProp.Title);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜