2010-01-21 4 views
0

Quand je lance le code ci-dessous, il fonctionneADO.NET Entity Framework Quirk

  int charId = int.Parse(Request.Params["charId"]); 
      EveFPT ctx = new EveFPT(); 
      var theCharQuery = from a in ctx.tblChars 
           where a.id == charId 
           select new 
              { 
               Name = a.name, 
               CorpName = a.tblCorps.name, 
               AllianceName = a.tblCorps.tblAlliances.name 
              }; 
      if(theCharQuery.Count() == 1) 
      { 
       var theChar = theCharQuery.First(); 
       lblCharName.Text = theChar.Name; 
       lblCorpName.Text = theChar.CorpName; 
       lblAllianceName.Text = theChar.AllianceName; 
      } 

Cependant, si je le ci-dessous

  var theCharQuery = from a in ctx.tblChars 
          where a.id == charId 
          select a; 
      if(theCharQuery.Count() == 1) 
      { 
       tblChars theChar = theCharQuery.First(); 
       lblCharName.Text = theChar.name; 
       lblCorpName.Text = theChar.tblCorps.name; 
       lblAllianceName.Text = theChar.tblCorps.tblAlliances.name; 
      } 

la déclaration

theChar.tblCorps 

retourne toujours null . Quelqu'un sait ce qu'il se passe?

Répondre

1

Entity Framework ne charge pas l'objet enfant avec impatience. Vous devez vérifier s'ils sont chargés, puis appeler Load() s'ils ne le sont pas.

if(!theChar.tblCorps.IsLoaded) 
{ 
    theChar.tblCorps.Load(); 
} 

Voici une bonne lecture de MSDN sur le sujet:

How to: Explicity Load Related Objects (Entity Framework)

1

Je pensais la même chose, même si je ne l'aurais pas attendu à avec impatience la charge dans l'expression de projection du premier exemple non plus. Une façon de l'essayer:

var charId= int.Parse(Request.Params["charId"]); 
EveFPT ctx = new EveFPT(); 
var theChar = (from a in ctx.tblChars.Include ("tblCorps") 
       where a.id == charId 
       select new 
       { 
        Name = a.name, 
        CorpName = a.tblCorps.name, 
        AllianceName = a.tblCorps.tblAlliances.name 
       }).FirstOrDefault(); 
if(theChar != null) 
{ 
    lblCharName.Text = theChar.Name; 
    lblCorpName.Text = theChar.CorpName; 
    lblAllianceName.Text = theChar.AllianceName; 
} 
Questions connexes