1

次のスニペットを検討してください。

// this.ctx is an instance of our EF Code First DB Context.
// the entity in this example is called "Something", and the DB set "Somethings".
// there is also another entity type called "SomethingElse".
// the Something entity is declared like this:
// 
// public class Something {
//   public int Foo { get; set; }
//   public string Bar { get; set; }
// 
//   public virtual IList<SomethingElse> RelatedStuff { get; set; }
// }
// 

// Create is used to ensure a proxy is created.    
var something = this.ctx.Somethings.Create();

// The new entity is added
this.ctx.Somethings.Add(something);    

// lazy loading: ON
System.Diagnostics.Debug.Assert(this.ctx.Configuration.LazyLoadingEnabled);    

// the entity is really in "added" state
System.Diagnostics.Debug.Assert(this.ctx.Entry(something).State == EntityState.Added);

// *** lazy loading does not work! ***
System.Diagnostics.Debug.Assert(something.RelatedStuff == null);

// note: if stepping through this with the debugger, I can confirm that "something" is
//       of the DynamicProxy type, not a plain "Something" POCO.

// but, if we change the state manually...
this.ctx.Entry(something).State = EntityState.Unchanged;

// *** it works!! ***    (doing a this.ctx.SaveChanges(), actually, also makes this work)
System.Diagnostics.Debug.Assert(something.RelatedStuff!= null);

遅延読み込みがオンでプロパティが仮想であり、状態を変更すると魔法のように機能し始めるのに、新しく作成されたPOCOの遅延読み込みが機能しない理由を誰かが説明できますか?私が間違っていなければ、一時的なオブジェクトであっても、遅延読み込みは機能するはずですよね?

乾杯、ティム

4

1 に答える 1

0

エンティティ フレームワーク 5 の遅延読み込み機能はデフォルトで無効になっているようです。Web では何も有用ではありませんでしたが、「DbContext」オブジェクトを定義した後、この機能をコードで明示的に設定する際の問題を突き止めました。

protected DbContext Context;
protected IDbSet<T> DbSet;

public Repository(DbContext context)
{
     Context = context;
     DbSet = Context.Set<T>();

     Context.Configuration.LazyLoadingEnabled = true;
}

これがお役に立てば幸いです。

于 2013-01-28T13:02:57.897 に答える