C#替代通用数据表

时间:2018-11-13 20:45:12

标签: c# oop datatable

请参阅以下内容:

public static DataTable GetSqlDataTable(string connStr, string strSqlStatement)
{
    DataTable dt = new DataTable();
    SqlDataAdapter dA = new SqlDataAdapter();

    try
    {
        SqlConnection conn = new SqlConnection(connStr);
        dA.SelectCommand = new SqlCommand(strSqlStatement, conn);
        dA.Fill(dt);
        return dt;
    }
    catch (Exception exc)
    {
        throw exc;
    }
}

如何使用object代替通用数据容器来避免这些通用数据表?

1 个答案:

答案 0 :(得分:1)

首先,您需要创建对象:

public class MyObj
{
    public string Name { get; set; }
    public int ID { get; set; }
}

然后在读取sql数据时创建对象:

private static IEnumerable<MyObj> ReadOrderData(string connectionString)
    {
        string queryString =
            "SELECT OrderID, CustomerID FROM dbo.Orders;";

        using (SqlConnection connection =
                   new SqlConnection(connectionString))
        {
            SqlCommand command =
                new SqlCommand(queryString, connection);
            connection.Open();

            SqlDataReader reader = command.ExecuteReader();

            // Call Read before accessing data.
            while (reader.Read())
            {
               yield return ReadSingleRow((IDataRecord)reader);
            }

            // Call Close when done reading.
            reader.Close();
        }
    }

    private static MyObj ReadSingleRow(IDataRecord record)
    {
        return new MyObj{ ID = record[0], Name = record[1]};
    }