2013-01-04 3 views
2

질문 : 데이터베이스 데이터를 해당 생성자의 클래스 인스턴스의 속성 및 필드에 채우고 싶습니다.생성자에 클래스 값을 지정 하시겠습니까?

public class Profile : ProfileOverview 
    { 

     public Profile() 
     { } 

     public Profile(long ProfileId) 
     { 
      using (System.Data.IDbCommand cmd = Settings.DAL.CreateCommand("SELECT * FROM Profiles WHERE ProfileId = @__in_profileid")) 
      { 
       Settings.DAL.AddParameter(cmd, "__in_profileid", ProfileId); 

       this = Settings.DAL.GetClass<Models.Profile>(cmd); 
      } // End Using cmd 

     } // End Constructor 

     ... (some properties and fields) 
} 

문제는 컴파일러가 쓰기 금지되어 있기 때문에 "this"를 할당 할 수 없다고 말합니다. "this"를 전달하기 위해 데이터베이스 추상화 계층을 변경해야하는지, 아니면 어떻게해야할까요?

문제는, GetClass 전화 Activator.CreateInstanceModels.Profile의 새로운 인스턴스를 생성하고, 나는 (GetClass 함수가 아닌 절차 때문에)이 그 방법을 유지하기 원합니다.

+0

이 코드는 처음에는 불량 디자인입니다. 생성자가 데이터베이스에서 데이터를 가져 오지 않아야합니다. – CodesInChaos

+0

생성자가 멤버 변수를 초기화하는 데 사용됩니다 ... not.also 자체도 수정할 수 없습니다 – Anirudha

+0

부채꼴 : 값 유형을 사용하는 경우 'this'에 지정할 수 있습니다. 하지만 여기서 가치 유형을 사용하지 마십시오. – CodesInChaos

답변

5

this을 할당 할 수 없습니다. 과 같이 당신의 패턴을 변경 고려 :
이 @CodeInChaos 및 @weston 의견을 바탕으로, 그것은 공평

public class Profile : ProfileOverview 
{ 

    public Profile() 
    { } 

    public static Profile Get(long ProfileId) 
    { 
     using (System.Data.IDbCommand cmd = Settings.DAL.CreateCommand("SELECT * FROM Profiles WHERE ProfileId = @__in_profileid")) 
     { 
      Settings.DAL.AddParameter(cmd, "__in_profileid", ProfileId); 

      return Settings.DAL.GetClass<Models.Profile>(cmd); 
     } // End Using cmd 
    } 

    ... (some properties and fields) 
} 

업데이트 나는 위의 코드는 나쁜 디자인 것을 여기에 추가하는 것이. 정적 로더 메서드는 Profile을로드하는 용도가 다른 클래스에있는 것이 이상적입니다. 다음 기본 예를 고려해보십시오.

public class Profile : ProfileOverview 
{ 
    public Profile() { } 

    ... (some properties and fields) 
} 

public class ProfileHelper 
{ 
    public Profile LoadProfileById(long ProfileId) 
    { 
     using (System.Data.IDbCommand cmd = Settings.DAL.CreateCommand("SELECT * FROM Profiles WHERE ProfileId = @__in_profileid")) 
     { 
      Settings.DAL.AddParameter(cmd, "__in_profileid", ProfileId); 

      return Settings.DAL.GetClass<Models.Profile>(cmd); 
     } 
    } 
} 
+0

작동하지만 여전히 나쁜 디자인입니다. – CodesInChaos

+0

@CodesInChaos. 약간 동의해라. 나는 보통 도우미 나 공장과 함께'Profile'을 만들거나로드 할 것입니다. –

+0

@CodesInChaos 동의합니다. 이제는 정적 인 방법 일뿐입니다. 유일한 직업은 데이터베이스에서'Profile's를로드하는 것입니다. – weston

관련 문제