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

Entity Framework は子オブジェクトを積極的に読み込みません。それらがロードされているかどうかを確認し、ロードされていない場合は Load() を呼び出す必要があります。

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

これについては、MSDN からの良い読み物です。

方法: 関連オブジェクトを明示的に読み込む (Entity Framework)

于 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 に答える