将查询结果分配给属性

时间:2017-12-10 23:32:29

标签: c# sql-server

每当我运行此查询并为对象的属性赋值时,它总是给我一个带有ADDRESS_ZIP列的erorr。每当我评论该特定分配时,值都会转到phoneHome属性。

这两列是" nchar"类型所以我认为这与它有关。但不能解决这个问题。

 public static Patient GetPatientInfo(string username)
    {
        SqlConnection connection = MedicalDB.EstConnection();
        string selectStatement
            = "SELECT PATIENT_ID, LAST_NAME, FIRST_NAME, USERNAME, DATE_Of_BIRTH, ADDRESS_STREET, ADDRESS_CITY, ADDRESS_STATE, ADDRESS_ZIP" +
            " PHONE_HOME, PHONE_MOBILE FROM PATIENT_TBL WHERE username = @username";

        SqlCommand selectCommand =
            new SqlCommand(selectStatement, connection);

        selectCommand.Parameters.AddWithValue("@username", username);

        try
        {
            connection.Open();
            SqlDataReader patientReader =
                selectCommand.ExecuteReader(CommandBehavior.SingleRow);
            if (patientReader.Read())
            {
                Patient patient = new Patient();
                patient.patientID = patientReader["PATIENT_ID"].ToString();
                patient.lastName = patientReader["LAST_NAME"].ToString();
                patient.firstName = patientReader["FIRST_NAME"].ToString();
                patient.userName = patientReader["USERNAME"].ToString();
                patient.DateOfBirth = patientReader["DATE_OF_BIRTH"].ToString();
                patient.addressStreet = patientReader["ADDRESS_STREET"].ToString();
                patient.addressCity = patientReader["ADDRESS_CITY"].ToString();
                patient.addressState = patientReader["ADDRESS_STATE"].ToString();
                patient.addressZip = patientReader["ADDRESS_ZIP"].ToString();
                patient.phoneHome = patientReader["PHONE_HOME"].ToString();
                patient.phoneMobile = patientReader["PHONE_MOBILE"].ToString();
                return patient;
            }
            else
            {
                return null;
            }
        }

        catch (SqlException ex)
        {
            throw ex;
        }
        finally
        {
            connection.Close();
        }

    }
  

未处理的类型' System.IndexOutOfRangeException'发生在System.Data.dll

1 个答案:

答案 0 :(得分:1)

您在ADDRESS_ZIP和PHONE_HOME之间缺少逗号(很难看到,因为您将它分成两行)。