2009-11-17 3 views
0

한다고 가정 내가 가진 같은 클래스 다음 의 C# - 클래스 디자인 문제 -로드 재산 목록

public class Stage 
{ 
    public int ID {get; set;} 
    public strint Code {get; set;} 
    public string Name {get; set;} 

    private List<Machine> _machines; 
    public List<Machine> Machines 
    { 
     get{ return _machines; } 
     set{ _machines = value; } 
    } 

    ......... 
    ......... 

    // This method returns all the Stages stored 
    // in the Stage-table in the database. 
    public static List<Stage> Get() 
    {  
    } 
} 

지금 문제는, 때 나는 _machines 목록을로드해야합니까?

나는이 방법을 예상 한 :

(1) Stage.Get() 방법에있어서 : 이것처럼

:

public static List<Stage> Get() 
{ 
    List<Stage> stages = null; 

    try 
    { 
     //Begin transaction... 


     //Retrieve all Stages and put them in List<Stage> stages 
     ................. 
     ................. 

     //End transaction... 

     if(stages!=null) 
     { 
      //Now load Machines for each Stage 
      for(int i=0 ; i<stages.Count ; i++) 
      { 
       //Get Machines by Stage ID and put them on List<Machine> 
       stages[i].Machines = Machine.Get(stages[i].ID); 
      } 
     }  
    } 
    catch(Exception ex) 
    { 
     stages = null; 

     throw ex; 
    } 

    return stages; 
} 

이 유일한 문제는 기계가 List<T>있는 경우입니다 - 속성을 (예 : List<Part> Parts 등) 및 Machine.Get(stages[i].ID) - 메서드가 비슷한 코딩을 사용하면 전체 테이블을 재귀 적으로로드하게됩니다. 그리고 이와 같이 전체 데이터베이스가 메모리에로드되었을 수도 있습니다.

(2) 부동산 직접 데이터베이스 액세스 :

private List<Machine> _machines; 
public List<Machine> Machines 
{ 
    get 
    { 
     //Get Machines by Stage ID and put them on List<Machine> 
     _machines = Machine.Get(this.ID); 

     return _machines; 
    } 
    set{ _machines = value; } 
} 

이의 문제가된다

이 큰 성능 손실에 종료됩니다 (I) :

Stage stage = Stage.Get(...ID...); 

foreach(Machine m in stage.Machine) 
{ 
    //Do something 
    .............. 
} 

Coz, 이러한 종류의 루프가 실행될 때마다 데이터베이스에 액세스해야합니다.

(ii) getsetSave(), Update() 등등에서 차별화되어야한다.

누구든지 저에게 더 좋은 방법을 제안 할 수 있습니까?

답변

2

디자인이 주어진다면 속성에 액세스 할 때마다 데이터를로드 할 필요가 없습니다. 대신, 아직 설정되었는지 확인하고 필요할 경우에만로드를 수행 할 수 있습니다. 이것은 lazy loading 디자인입니다.

private List<Machine> _machines; 
public List<Machine> Machines 
{ 
    get 
    { 
     //Get Machines by Stage ID and put them on List<Machine> 
     //only if we have not already done so 
     if (_machines == null) 
     { 
      _machines = Machine.Get(this.ID); 
     } 

     return _machines; 
    } 
    set{ _machines = value; } 
} 
+0

+1 나는 똑같은 것을 쓰고, 상쾌하게하고, presto했다; 당신은 이미 그것을 썼습니다. – DancesWithBamboo

+0

따라서 null 체크만으로 차이를 만들고 있습니다. – anonymous