开发者

ADO.NET Entity Framework Quirk

开发者 https://www.devze.com 2022-12-18 04:27 出处:网络
When I run the code below, it works int charId = int.Parse(Request.Params[\"charId\"]); EveFPT ctx = new EveFPT();

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

精彩评论

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

关注公众号