2010-01-21 244 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; 
}