0

当我运行下面的代码时,它可以工作

            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。有谁知道发生了什么?

4

2 回答 2

1

实体框架不会急切地加载子对象。您必须检查它们是否已加载,如果未加载,则调用 Load()。

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

这是 MSDN 关于该主题的好读物:

如何:显式加载相关对象(实体框架)

于 2010-01-21T14:10:56.813 回答
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;
}
于 2010-01-21T14:26:23.183 回答