2010-12-08 44 views
2

我有一個場景,我需要拉大約7500數據庫記錄,其中每個記錄有6個子實體列表。這些兒童名單中的每一個都可以是0到大約125條記錄。將成千上萬的子記錄帶入類對象的成千上萬條記錄最有效的方法是什麼?

我的階級結構那種看起來是這樣的:

public class Entity 
{ 
    public int ID { get; set; 
    public string Name { get; set; } 
    public ICollection<ChildEntity1> Children1 { get; set; } 
    public ICollection<ChildEntity2> Children2 { get; set; } 
    public ICollection<ChildEntity3> Children3 { get; set; } 
    public ICollection<ChildEntity4> Children4 { get; set; } 
    ... 2 more collections 
} 

我檢索所有實體之後,我需要遍歷每一個和執行一些計算,調用一些Web服務和其他各種各樣的東西,並最終導出到文件。

什麼是使用C#4從MS Sql Server 2008中檢索這些數據的最佳策略? DataAdapters是DataSet的最佳方式嗎? ORM?

我想遠離選擇N + 1場景,原因很明顯。

+1

你是否需要同時在內存中的所有實體,或者你可以獲取一個實體的子集,處理它們,並將它們寫入文件? – 2010-12-08 16:49:50

回答

0

所以我落得這樣做有一個嵌套的DataReader,一個外一個父實體把所有的父母,然後一個內一個用該閱讀器讀取所有的孩子在一個語句.NextResult()方法與此類似:

var exampleSql = "select * from child1Table; " + 
       "select * from child2Table; " + 
       "select * from child3Table"; 
       // and so on for the other child tables 
using (var outerReader = cmd.ExecuteReader()) 
{ 
    while (outerReader.Read()) 
    { 
     var entity = new Entity(); 
     entity.Prop1 = outerReader[0]; 
     entity.Prop2 = outerReader[1]; 
     //.... etc. 

     using (var cmdInner = new SqlCommand(exampleSql)) 
     using (var innerReader = cmdInner.ExecuteReader()) 
     { 
      while (innerReader.Read()) 
      { 
       var child = new Child1(); 
       child.Prop1 = innerReader[0]; 
       // ... etc. 
       entity.Children1.Add(child); 
      } 
      innerReader.NextResult(); 
      while (innerReader.Read()) 
      { 
       var child = new Child2(); 
       child.Prop1 = innerReader[0]; 
       // ... etc. 
       entity.Children2.Add(child); 
      } 
      innerReader.NextResult(); 
      // and so on for the other child entities 
     } 
    } 
} 

至少這樣,我只發送一條SQL語句到數據庫中每個孩子家長來檢索所有我的孩子實體的每父,而不是一個單獨的聲明。

如果有人有更好的方法,隨時讓我知道。

順便說一句,我的示例代碼只是僞代碼。真正的事情是使用參數化查詢,並沒有選擇明星,只是我需要的列。目的是展示方法,而不是實際的實現。

0
DECLARE CURSOR on the Entity. 

OPEN CURSOR. 

For each FETCH CURSOR 

    SELECT the child rows for the current Entity. 

    Write the output. 

CLOSE CURSOR. 
相關問題