2010-08-22 2 views
1

메신저 데이터베이스에서 데이터를 동적으로 가져 오려고합니다. 나는 ...을 heres 내가 여기 DataReader를 사용하여 datas를 얻을 수 있습니다 내 문제는 코드 list<T> select<T>() 방법입니다했습니다목록에 유형을 추가하는 방법 <T> C# 4,0

public list<T> Select<T>() 
{ 
    Type type = typeof(T); 
    ... 
    ... 
    using (SqlConnection connection = new SqlConnection(ConnectionString)) 
    { 
     try 
     { 
       SqlCommand sqlCommand = new SqlCommand(selectCommand, connection); 
       connection.Open(); 
       SqlDataReader sqlReader = sqlCommand.ExecuteReader(); 
       while (sqlReader.Read()) 
       { 
        foreach (PropertyInfo property in type.GetProperties()) 
        { 
         property.SetValue(property.Name,(PropertyInfo)sqlReader[property.Name],null); 

        } 
        typeList.Add((T)Convert.ChangeType(type,typeof(T))); 
       } 
       sqlReader.Close(); 
     } 
     catch (Exception ex) 
     { 
       string exc = ex.Message; 
     } 
     finally 
     { 
       connection.Close(); 
     } 
    } 
    return typeList; 
} 

내가 데이터를 얻을 수 있지만 난 그래서 난 내 typelist에 내 유형을 추가 할 수 없습니다 내 타입에 할당 할 수 없습니다 도와주세요

+0

, 당신이 질문을 편집 코드를 선택하고의 코드 버튼을 누릅니다 편집기 (101 \ 010을 가진 편집기). –

+0

코드가 불완전하여 typeList 선언이 누락되었습니다. –

답변

0

변환하려는 데이터 유형은 무엇입니까? 당신은 아마도 쿼리를 기반으로 데이터를 선택해야합니다. 이것은 무작위로 제공되는 하나의 유형에 전체 데이터베이스를 저장하려는 것과 같습니다. 이중에 텍스트를 저장하려고 할 수 있습니다 ...

데이터베이스의 모든 데이터를 저장하려면 DataSet 또는 DataTable을 사용하십시오.

여기 도대체 뭐하고 있니? 당신이 요청 된 유형의 속성 이름을 변경하려고처럼

property.SetValue(property.Name,(PropertyInfo)sqlReader[property.Name],null); 

당신이 그것을 인스턴스화 할 필요가 유형에 속성을 할당 할 수있는 전 ...

1

을 보이는 :

T instance = Activator.CreateInstance<T>(); 
foreach (PropertyInfo property in type.GetProperties()) 
{ 
    property.SetValue(instance, sqlReader[property.Name], null); 
} 
typeList.Add(instance); 

SqlCommand을 올바르게 처분하기 위해 using 블록에 포장하십시오. 또 다른 말은 .Close() finally 블록에 연결이 필요하지 않다는 것입니다. using 블록에서 이미 연결을 래핑 했으므로 Dispose 메서드에 의해 자동으로 수행됩니다.

+0

감사합니다. 많은 답변을 찾았지만 이것도 유용합니다. –

1

각 데이터베이스 행에 대해 유형 T의 오브젝트를 작성하려는 것처럼 보입니다.

그럼 당신은 빈 생성자를 가진 클래스로 제네릭 제약 조건 수 있습니다

public List<T> Select<T>() where T : new() 

당신이 만들 수있는 새 T의

while (sqlReader.Read()) 
{ 
    T item = new T(); 
    foreach (PropertyInfo property in type.GetProperties()) 
    { 
     // Note the first parameter "item" 
     property.SetValue(item, sqlReader[property.Name], null); 
    } 
    typeList.Add(item); 
} 
+0

덕분에 많은 답변을 찾았습니다. –

관련 문제