2017-01-23 18 views
0

遅延読み込みを使用してICollectionオブジェクトを読み込む際に問題が発生します。遅延読み込みでICollectionプロパティが読み込まれない

public class Product 
{ 
    [Key] 
    public int Id { get; set; } 
    public string OrderNum { get; set; } 
    public DateTime DateOfPurchased { get; set; } 
    public int CustomerId { get; set; } 
    public virtual ICollection<OrderedItem> OrderedItems { get; set; } 

    public virtual Customer Customer { get; set; } 
} 

public class OrderedItem 
{ 
    [Key] 
    public int Id { get; set; } 
    public int ProductId { get; set; } 
    public int? Quantity { get; set; } 
    public int? ItemId { get; set; } 
    public decimal? TotalPrice { get; set; } 
    public decimal? Profit { get; set; } 

    public virtual Item Item { get; set; } 
    public virtual Product Product { get; set; } 
    } 

私はProductにデータをロードするたびに、すべてのプロパティがICollectionプロパティを除いてロードすることができます。私は間違いを犯しましたか?

+0

は、移行ファイルで定義された外部キーはありますか? –

+0

@Bérangerはい。 OrderedItemの作成時に外部キーが定義されています –

+0

@hafizabdullah ICollectionオブジェクトにアクセスする前にコンテキストを破棄しましたか? –

答えて

1

こんにちは、私はこれを私のローカルPCで試してみました。以下はModelクラスとdbContextクラスです。私はそれを簡単にするためにいくつかのプロパティを削除しました。ちょうどモデル作成時に私は1行追加しました。

EFクラス

 public class Product 
      { 
       [Key] 
       public int Id { get; set; } 
       public string OrderNum { get; set; } 
       public DateTime DateOfPurchased { get; set; } 
       public int CustomerId { get; set; } 
       public virtual ICollection<OrderedItem> OrderedItems { get; set; } 


      } 

      public class OrderedItem 
      { 
       [Key] 
       public int Id { get; set; } 
       public int ProductId { get; set; } 
       public int? Quantity { get; set; } 
       public int? ItemId { get; set; } 
       public decimal? TotalPrice { get; set; } 
       public decimal? Profit { get; set; } 

       public virtual Product Product { get; set; } 
      } 

MY DBCOntextクラス:

 public class SampleDbContext : DbContext 
    { 
     public SampleDbContext() 
      : base("name=SampleDBConnection") 
     { 
      this.Configuration.LazyLoadingEnabled = true; 
      this.Configuration.ProxyCreationEnabled = true; 
     } 



     public DbSet<Product> Products { get; set; } 

     public DbSet<OrderedItem> OrderedItems { get; set; } 



     protected override void OnModelCreating(DbModelBuilder modelBuilder) 
     { 

      modelBuilder.Entity<Product>().HasMany(c => c.OrderedItems); 



     } 
    } 

出力:enter image description here

+0

答えをありがとう。 Fluent APIを使用して解決しました –

+0

@hafizabdullah嬉しいです。私の答えと説明が欲しいと願っています。 –