Skip to main content
 首页 » 编程设计

c#之为字段填充返回 SQL DataRow 的正确方法

2024年02月23日11mayingbao

我有以下场景,我一直使用它从 SQL 数据库返回单行。返回数据后,我只是用它来填充网络表单上的字段。

示例数据库类:

public class DBAccess 
{ 
    public DataTable ReturnContactInfo(int userID) 
    { 
        // executes a stored procedure, populates a datatable, then returns it 
    } 
} 

使用该类填充理论上的客户名称字段的示例:

protected void Page_Load(object sender, EventArgs e) 
{ 
    if(!isPostBack) 
    { 
        DBAccess db = new DBAccess(); 
        DataTable dt =  db.ReturnContactInfo(1); 
        if (dt.Rows.Count > 0) 
        { 
           customerName.Text = Convert.ToString(dt.Rows[0]["customerName"]); 
        } 
     } 
} 

是否有更好或更有效的方法(“this”返回单个数据行以从中提取数据)?这种方法当然有效,但是当我总是并且只会使用索引 0 处的行时,必须键入 dt.Rows[0][string] 有点麻烦。请记住我喜欢能够将所有数据层的东西提取到一个类中。这(据我所知)意味着我不能使用 SqlDataReader,因为它必须在完成后关闭,所以我不能从我的数据层类中返回它。

请您参考如下方法:

用您想要的成员定义一个类作为属性。然后填充并返回该对象。您可以使用诸如“dapper”之类的工具使这变得简单:

public Customer GetCustomer(int id) 
{ 
     return connection.Query<Customer>("getCustomer", 
         new {id}, // <=== param 
         commandType: CommandType.StoredProcedure).Single(); 
} 

然后:

var cust = GetCustomer(12345); 
string name = cust.Name; 

现在:

  • 很明显我们只有一个对象
  • 对象上的成员明显且类型良好
  • 避免了 DataTable 的大量开销