2016-10-21 106 views
0

我想用來自SQL Server查詢的數據填充我的主詳圖對象。從SQL查詢填充對象

但是,我似乎沒有正確形成查詢的細節部分。

這有可能嗎?

我有以下類

public class OrderCountReportHeader : IMyReport 
{ 

    [Key] 
    public int Id { get; set; } 
    public DateTime RunAt { get; set; } 
    public string Name { get; set; } 
    public virtual List<OrderCountReportDetail> Details { get; set; } 

} 

public class OrderCountReportDetail { 
    public virtual OrderBankReportHeader Header { get; set; } 
    public string ProductCode { get; set; } 
    public int Quantity { get; set; } 

}

,我想從一個SQL查詢

private static string ReportSql() { 

     return @" 
       SET NOCOUNT ON; 
       select 1 as Id, getdate() as RunAt, 'test' as Name; 
       select 'RC' as ProductCode , 5 as Quantity; " 
      ; 
    } 

var result = context.Database.SqlQuery<OrderCountReportHeader>(sql).ToArray()[0]; 

    Assert.AreEqual(@"test", s.Name); // true 
    Assert.AreEqual("RC", s.Details[0].ProductCode); // fails because Details is null 

回答

0

輸出填充OrderCountReportHeader的實例,我結束了使用兩個單獨的調用SqlQuery 雖然我很樂意知道更好的方法。

var header = connect.Database.SqlQuery<OrderCountReportHeader>(ReportSqlHeader()).ToArray()[0]; 

      var details = connect.Database.SqlQuery<OrderCountReportDetail>(ReportSqlDetails()).ToList(); 
      foreach (var det in details) 
      { 
       det.Header = header; 
      } 
      header.Details = details;