我尝试从中提取数据的SQL Server中的表包含以下列:
名称|性别|工资|系
在下面的代码中,我要做的就是从表中提取员工信息,从该信息中创建员工对象,然后将该对象添加到员工列表中。 这是代码:
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() { }
}
}
当我在调试模式下运行上面的代码时(在Visual Studio中),代码中断并且以下代码以黄色突出显示:
returnList.Add(
new Employee
{
name = reader.GetString(0),
gender = reader.GetChar(1),
salary = reader.GetInt16(2),
department = reader.GetString(3)
}
);'
答案 0 :(得分:0)
首先,您应该检查结果中是否存在任何行。 使用此代码,您可以检查:
if (reader.HasRows)
如果employee表和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块(在此行之后):
if (SQLConnectingTools.CheckConnection(connectionString))