我有一个SQL模板方法,我想返回一个字符串以及执行查询的各种方法,我想从中获取字符串:
private string sqlQueryReturnString(Action<SqlConnection> sqlMethod)
{
string result = "";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
try
{
//open SQL connection
conn.Open();
result = sqlMethod(conn);
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex.ToString());
}
finally
{
conn.Close();
}
return result;
}
//Get the primary key of the currently logged in user
private string getPKofUserLoggedIn(SqlConnection conn)
{
int result = 0;
SqlCommand getPKofUserLoggedIn = new SqlCommand("SELECT [PK_User] FROM [User] WHERE [LoginName] = @userIdParam", conn);
//create and assign parameters
getPKofUserLoggedIn.Parameters.AddWithValue("@userIdParam", User.Identity.Name);
//execute command and retrieve primary key from the above insert and assign to variable
result = (int)getPKofUserLoggedIn.ExecuteScalar();
return result.ToString();
}
以上是我认为这是如何接近的。这就是电话:
string test = sqlQueryReturnString(getPKofUserLoggedIn);
这部分不起作用:
result = sqlMethod(conn);
看来sqlMethod被认为是无效的。
如何获得我想要的功能?
答案 0 :(得分:5)
你想要一个Func<SqlConnection, string>
。 Action
用于void
方法,Func
用于返回某些内容的方法。