WCF服务返回DataSet

时间:2016-01-03 17:19:13

标签: c# wcf datagridview dataset odbc

我有这个WCF服务:

public DataSet GetInfo()
{
        DataTable dt = new DataTable("Tbl");
        DataSet ds = new DataSet("Set");        
        OdbcCommand OdbcCmd;
        OdbcCmd = new OdbcCommand("select * FROM Products where id = 'JBE-235'", OdbcConn);          
        OdbcConn.Open();
        dt.Load(OdbcCmd.ExecuteReader());
        ds.Tables.Add(dt);           
        OdbcConn.Close();          
        return ds;
}

但是我已经知道从WCF服务返回DataSet是一种不好的做法,我有一个桌面应用程序,我需要用DataGridView填写服务' s结果

private void ButtonInfo_Click(object sender, EventArgs e)
{ 
     WCFService service = new WCFService();
     DataGridView1.DataSource = service.GetInfo();
     service.Close();
}

我应该从WCF服务获取哪种数据类型以正确填充DataGridView

提前致谢。

1 个答案:

答案 0 :(得分:3)

更好的方法是返回DTO(在您的情况下,它将是DTO的集合)。

首先,创建将包含Products表中的预期字段的DTO类。例如:

public class Product
{
    public string Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

接下来,通过DataReader

从数据库中读取值
// use IEnumerable<Product> for .net <= 4.0 and IReadOnlyCollection<Product> for .net >= 4.5
public IReadOnlyCollection<Product> GetInfo()
{
    OdbcCommand command = new OdbcCommand("select * FROM Products where id = 'JBE-235'", OdbcConn);          
    OdbcConn.Open();
    var reader = command.ExecuteReader();
    var products = new List<Product>();
    while (reader.Read())
    {
        var product = new Product();
        // reader index is the column name from query
        // You can also use column index, for example reader.GetString(0)
        product.Id = (string) reader["id"];
        product.Name = (string) reader["name"];
        product.Price = (decimal) reader["price"];
        products.Add(product);
    }
    return products;
}

请注意,您需要在读取所有数据后关闭连接,然后好的做法是使用using语句自动将其置于方法的末尾。另一个建议是使用命令Parameters

// use IEnumerable<Product> for .net <= 4.0 and IReadOnlyCollection<Product> for .net >= 4.5
public IReadOnlyCollection<Product> GetInfo()
{
    using(var con = GetConnection())
    {
        var cmd = new OdbcCommand("select * FROM Products where id = @Id", con);
        cmd.Parameters.AddWithValue("@Id", "JBE-235");
        con.Open();
        var reader = cmd.ExecuteReader();
        var products = new List<Product>();
        while (reader.Read())
        {
            products.Add(new Product { Id = (string) reader["id"], Name = (string) reader["name"], Price = (decimal) reader["price"] });
        }
        return products;
    }
}