2012-06-19 220 views
0

我有這些類,我正在使用存儲庫模式,並試圖讓IEnumerable包含WorkOrderDetail。我是MVC和實體框架的新手,我無法弄清楚如何包含WorkOrderDetails。實體框架關係Foreach

public IEnumerable<Schedule> GetFuture() 
     { 
      string tZone = "Pacific Standard Time"; 

      DateTime today = Today(tZone); 

      var schedule = context.Schedules 
       .Where(s => s.Date >= today).ToList();    

      return schedule; 
     } 

public abstract class Entity 
    { 
     public int Id { get; set; } 
    } 

public class Schedule : Entity 
    { 
     public DateTime Date { get; set; } 

     public bool Free { get; set; } 

     public int WorkOrderId { get; set; } 
     public virtual WorkOrder WorkOrder { get; set; }   
    } 

public class WorkOrder : Entity 
    { 

     public string Name { get; set; } 
     public string Type { get; set; } 

     public virtual ICollection<WorkOrderDetail> WorkOrderDetails { get; set; } 
    } 
public class WorkOrderDetail : Entity 
    { 
     public string Job { get; set; } 
     public bool Finished { get; set; } 
    } 

回答

1

更改此:

var schedule = context.Schedules.Where(s => s.Date >= today).ToList();  

到:

var schedule = context.Schedules.Include("WorkOrder.WorkOrderDetail").Where(s => s.Date >= today).ToList(); 
+0

或者與EF 4.1 +你可以使用lambda語法,'.INCLUDE(S​​ =>取值WorkOrder.WorkOrderDetail。)' –

+0

@LukeMcGregor我試過這個,但是當我嘗試在視圖'foreach(模型中的變量細節)中訪問作業時) {detail.WorkOrder.WorkOrderDetail.Job }'它不起作用。 – flean

+0

@flean當你嘗試時會發生什麼,你會得到一個異常嗎?如果是這樣,它是什麼? – CodingGorilla