EF4コンテキストでレイジーローディングを有効にしようとしています。InEntity Framework 4でレイジーローディングが動作しない
データをロードしようとしているコードは次のとおりです。
using (IUnitOfWork uw = new EFUnitOfWork())
{
foreach (Document doc in uw.Documents.All)
{
Console.WriteLine("Name: {0} Description: {1} Category: {2}", doc.Name, doc.Description, doc.DocumentCategory.Name);
}
}
私は仕事のパターンのリポジトリとユニットを試していますが、私はそれを理解するよう、以下のコマンドが動作するはずです。
ctx.ContextOptions.LazyLoadingEnabled = true;
問題は、doc.DocumentCategory.NameにアクセスするとNullReferenceExceptionが発生することです。
なぜこのデータが遅延して読み込まれないのですか?
DocumentCategoriesが読み込まれている場合、DocumentCategoryプロパティが解決されます。
次のようにマイドキュメントクラスが定義されています
public class Document
{
public Document()
{
}
public Document(int id)
{
Id = id;
}
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual string Description { get; set; }
public virtual int DocumentCategoryId { get; set; }
public virtual bool Deleted { get; set; }
public DocumentCategory DocumentCategory { get; set; }
public override string ToString()
{
return Name;
}
}
Do * all *ドキュメントにはDocumentCategoryがありますか? LazyLoadingが指定されたDocumentのDocumentCategoryを取得しようとしたためにnoneが見つかった場合は、nullを返してNullReferenceExceptionを引き起こします。 – Smudge202
はい、DocumentCategoryIdはデータベース内のnull不可能なフィールドであり、テーブル間に外部キーが存在します。 –
ナビゲーションプロパティは仮想としてマークされていますか? Documentクラスの定義を教えてください。 – Dave