2016-09-29 59 views
1

如何從dbWagonList返回doc使用Include()С#來自嵌套對象的Enitity Framework返回列表

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Document document = new Document(); 
      document.Id = 73243; 
      document.Name = "SendingForm"; 
      document.Wagons = new Wagons 
      { 
       Depos = "Main", 
       Id = 1, 
       Street = "WestSide", 
       WagonList = new List<Wagon> 
      { 
       new Wagon {Code="MP",Destination="China",Id=1,Number=90543 }, 
       new Wagon { Code="MO",Destination="Bangkok",Id=2,Number=90543}, 
       new Wagon {Code="MI",Destination="Burma",Id=3,Number=90543 } 
      } 
      }; 
      using (var db = new SoccerContext()) 
      { 
       //db.documents.Add(document); 
       //db.SaveChanges(); 
       Document doc = db.documents.Include("Wagons").FirstOrDefault(); 
      } 
     } 
    } 

    public class Document 
    { 
     [Key] 
     public int Id { get; set; } 

     public string Name { get; set; } 

     public Wagons Wagons { get; set; } 
    } 

    public class Wagons 
    { 
     [Key] 
     public int Id { get; set; } 

     public string Depos { get; set; } 

     public string Street { get; set; } 

     public List<Wagon> WagonList { get; set; } 
    } 

    public class Wagon 
    { 
     [Key] 
     public int Id { get; set; } 

     public string Code { get; set; } 

     public int Number { get; set; } 

     public string Destination { get; set; } 
    } 

    class SoccerContext : DbContext 
    { 
     public SoccerContext() 
      : base("DocumentDB") 
     { } 

     public DbSet<Document> documents { get; set; } 
    } 
} 
+1

什麼是不工作的準確? 'Document doc = db.documents.Include(x => x.WagonList).FirstOrDefault();'應該工作。即使您沒有使用Include,EF在您訪問WagonList屬性時也會延遲加載貨車。 – Howwie

回答

2

對於single Document object,其直截了當:

var wagonList = doc.Wagons.WagonList 

對於List of Documents做到這一點(將扁平化文檔層次內貨車的列表):

var wagonList = docList.SelectMany(doc => doc.Wagons.WagonList);