views:

37

answers:

2

Hi,

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 below

            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?

+1  A: 

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)

Justin Niessner
+1  A: 

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