开发者

ADO.NET Entity Framework Quirk

When I run the code below, it works

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

However, If I the belo开发者_开发百科w

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

the statement

theChar.tblCorps

always returns null. Anyone know what's happening?


The Entity Framework doesn't eagerly load child object. You have to check if they're loaded, and then call Load() if they're not.

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

Here's a good read from MSDN on the subject:

How to: Explicity Load Related Objects (Entity Framework)


I was thinking the same thing, although I wouldn't have expected it to eagerly load in the first example's projection expression either. Once way to try it:

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜