【问题标题】:C# abstraction and database layer and delegatesC# 抽象和数据库层和委托
【发布时间】:2012-11-22 17:15:12
【问题描述】:

我能否得到一些帮助来解释下面的这个答案以及它如何与代表一起工作。它的答案来自这里:C# abstraction and database layer

...如果您坚持使用 DataReader 的想法,您可以将委托传递给助手,该助手在 using 语句中被调用:

public string GetMySpecId(string dataId)
{
    return _dbHelper.ExecuteQuery(
        dr => 
           {
               if(dr.Read())
               {
                   return dr[0].ToString();
               }
               // do whatever makes sense here.
           },
        @"select ""specId"" from ""MyTable"" where ""dataId"" = :dataId",
        new SqlParameter("dataId", dataId));
    return result.Rows[0][0].ToString();
}

您还可以使用像 Dapper 这样的轻量级工具来简化一些语法并负责映射到您的数据类型。 (您仍然需要处理打开连接等问题。)

【问题讨论】:

  • 需要说明哪一部分?
  • 如果你看另一个问题中的例子,你如何声明ExecuteQuery,为什么这里有2个return语句?
  • 就 2 个返回语句而言,它看起来像是一个错字,我认为他的意思是把第一个返回的位置是 var result。我会看看能不能找到一个关于如何使用委托的例子。
  • cool thx,我是一名过渡到 .net 的 php 程序员
  • 别担心,只是想找到一个好的例子,挖掘一些旧代码

标签: c# .net .net-3.5 data-access-layer sqlcommand


【解决方案1】:

从上面声明ExecuteQuery 方法应该如下所示:

public DataTable ExecuteQuery(Func<DataReader, DataTable> delegateMethod, string sqlQuery, SqlParameter param)
    {
        using (SqlConnection conn = new SqlConnection(this.MyConnectionString))
        {
            conn.Open();

            // Declare the parameter in the query string
            using (SqlCommand command = new SqlCommand(sqlQuery, conn))
            {
                // Now add the parameter to the parameter collection of the command specifying its type.
                command.Parameters.Add(param);

                command.Prepare();

                // Now, add a value to it and later execute the command as usual.
                command.Parameters[0].Value = dataId;


                using (SqlDataReader dr = command.ExecuteReader())
                {
                   return delegateMethod(dr);
                }
            }
        }
    }

应该是的,你可能需要在Func中交换DataReader和DataTable,我不记得参数类型和返回类型哪个在前。

这是使用Func 委托的另一个示例,如果您不需要返回类型,还有Action 委托。

Func Delegate Reading Normal Delegate Reading

【讨论】:

    猜你喜欢
    • 2012-11-22
    • 1970-01-01
    • 1970-01-01
    • 2010-09-08
    • 2011-02-19
    • 2010-12-13
    • 2015-05-15
    • 1970-01-01
    • 2012-06-14
    相关资源
    最近更新 更多