2017-10-28 17 views
0

데이터를 추출하려고하는 SQL Server의 테이블에 다음 열이 있습니다.목록에 개체를 추가 할 때 NotSupportedException 가져 오기

이름 | 성별 | 급여 | department

아래 코드에서 테이블에서 직원 정보를 추출하고 해당 정보에서 직원 개체를 만든 다음 해당 개체를 직원 목록에 추가하기 만하면됩니다. 내가 (Visual Studio에서) 디버그 모드에서 위의 코드를 실행하면 코드를 중단하고 다음 코드는 노란색 강조

namespace LINQQueriesPart2 
{ 
    class Program 
    { 
     List<Employee> whatever = EmployeeDB.getEmployees(); 

     IEnumerable<Employee> query = from y in whatever 
             where y.name[0] == 'M' 
             select y; 

     foreach (Employee x in query) 
     { 
      Console.WriteLine(x.name); 
     } 
    } 
} 

namespace ConnectingToSql 
{ 
    public static class EmployeeDB 
    { 
     public static List<Employee> getEmployees() 
     { 
      List<Employee> returnList = new List<Employee>(); 

      String connectionString = "server=DESKTOP-T5KDKOP;" 
            + "database=MCP_Exam_70-483_Prep;" 
            + "Trusted_Connection=yes"; 

      if (SQLConnectingTools.CheckConnection(connectionString)) 
      { 
       SqlConnection connection = new SqlConnection(connectionString); 
       connection.Open(); 
       SqlCommand command = new SqlCommand("SELECT * FROM employees", connection); 

       SqlDataReader reader = command.ExecuteReader(); 
       while (reader.Read()) 
       { 
        returnList.Add(
         new Employee 
         { 
          name = reader.GetString(0), 
          gender = reader.GetChar(1), 
          salary = reader.GetInt16(2), 
          department = reader.GetString(3) 
         } 
        ); 
       } 
       reader.Close(); 

       connection.Close(); 
      } 
      else 
      { 
       Console.WriteLine("SQL connection is not successful."); 
      } 
      return returnList; 
     } 
    } 

    public class Employee 
    { 
     public String name { get; set; } 
     public char gender { get; set; } 
     public int salary { get; set; } 
     public String department { get; set; } 

     public Employee() { } 
     } 
    } 

: 모든 당신의

returnList.Add(
    new Employee 
    { 
     name = reader.GetString(0), 
     gender = reader.GetChar(1), 
     salary = reader.GetInt16(2), 
     department = reader.GetString(3) 
    } 
);' 
+0

메시지 및 내부 예외 메시지가 표시됩니까? 그리고 SELECT SELECT * FROM employees 쿼리에서 얻는 결과 집합의 열 유형은 무엇입니까? – Shyju

+0

직원을 DataTable에보다 쉽게로드 할 수 있습니다. 마찬가지로, 만약 당신이'SELECT *'당신은 정말로 어떤 순서로 컬럼이 돌아 왔는지 제어하지 않는다. 당신은 GetInt16()을 통해 날짜를 얻으려고 할 수있다. – Plutonix

답변

0

먼저 여기 코드입니다 결과에 행이 있는지 확인해야합니다. 이 코드 당신은을 확인할 수 있습니다

if (reader.HasRows) 

직원 테이블의 디자인과 Employee 객체가 다른 경우가 System.NotSupportedException 또는 System.InvalidCastException을받을 수 있으며, 잘못된 캐스트를 시도하거나에 데이터가 없었다 경우 결과 System.NotSupportedException이 발생합니다.

나는 코드에서 몇 가지 개선을 만든이 작동해야합니다

using (SqlConnection cn = new SqlConnection(connectionString)) 
{ 
    string commandText = "SELECT * FROM employees"; 
    using (SqlCommand cmd = new SqlCommand(commandText, cn)) 
    { 
     cmd.CommandText = commandText; 

     cn.Open(); 
     SqlDataReader reader = cmd.ExecuteReader(); 
     if (reader.HasRows) 
     { 
      while (reader.Read()) 
      { 
       var employeeColumns = new object[4]; 
       var colCount = reader.GetSqlValues(employeeColumns); 
       returnList.Add(
        new Employee 
        { 
         name = employeeColumns[0].ToString(), 
         gender = employeeColumns[1].ToString()[0], 
         salary = Convert.ToInt16(employeeColumns[2].ToString()), 
         department = employeeColumns[3].ToString() 
        } 
       ); 
      } 
     } 
    } 
} 

그냥 (이 선 후) 그 위에 당신의 경우 블록 코드를 복사 :

정확한 예외 무엇
if (SQLConnectingTools.CheckConnection(connectionString))