如何读取和写入SQL Server数据库中的对象?

时间:2017-02-26 03:47:29

标签: c# sql-server database

我的第一个表是Clinics,其中包含列:

ClinicId, ClinicName, ClinicShortName

我的第二个表是Employees,其中包含列:

EmployeeId, EmployeeName, ClinicId, OnJob

我还有一个视图v_employees定义为:

SELECT   
    Employees.EmployeeId, Employees.EmployeeName, 
    Clinics.ClinicShortName, 
    Employees.OnJob
FROM     
    Clinics 
INNER JOIN
    Employees ON Clinics.ClinicId = Employees.ClinicId

我的C#代码是:

class Employee
{
    public int EmployeeId { get; set; }
    public string EmpolyeeName { get; set; }
    public int ClinicId { get; set; }
    public bool OnJob { get; set; }
}

class Clinic
{
    public int ClinicId { get; set; }
    public string ClinicName { get; set; }
    public string ClinicShortName { get; set; }
}

List<Employee> employeeList = new List<Employee>();

private void InitEmployees()
{
    SqlConnection con = new SqlConnection(......);

    SqlCommand cmd = new SqlCommand("select * from v_employees", con );
    con.Open();

    SqlDataReader dr = cmd.ExecuteReader();

    while (dr.Read())
    {
        Employee employee = new Employee()
            {
                EmployeeId = Convert.ToInt32(dr["EmployeeId"]),
                EmpolyeeName = dr["EmployeeName"].ToString(),
                // how to use ClinicShortName field in this position?
                // Because I want the data to be displayed into DataGridView control.
                OnJob = Convert.ToBoolean(dr["OnJob"])
            };

        employeeList.Add(employee);
    }

    dr.Close();
    con.Close();

    dataGridView1.DataSource = employeeList;
}

如何将对象导入SQL Server?

我应该使用List<T>方法吗?

1 个答案:

答案 0 :(得分:0)

您必须在ClinicShortName课程中添加employee字段,但为什么不使用sqladapter?它根据返回的数据生成列

    SqlConnection con = new SqlConnection(......);
    SqlCommand cmd = new SqlCommand("select * from v_employees", con );
    con.Open();
    DataTable table = new DataTable();
    SqlDataAdapter adapter = new SqlDataAdapter(cmd);

    adapter.Fill(table);
    dr.Close();
    con.Close();
    dataGridView1.DataSource = table;