2010-01-21 208 views
0

當我運行下面的代碼,它的工作原理ADO.NET實體框架夸克

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

但是,如果我下面的

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

聲明

theChar.tblCorps 

總是返回null 。任何人都知道發生了什麼?

回答

1

實體框架並不急切地加載子對象。你必須檢查它們是否被加載,然後調用Load(),如果它們不是。

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

這裏有一個良好的閱讀從MSDN上的主題:

How to: Explicity Load Related Objects (Entity Framework)

1

我想同樣的事情,雖然我也沒有想到它在第一個例子中的投影表達熱切負載無論是。一次嘗試的方法:

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