David Tunnell
David Tunnell

Reputation: 7532

Return a string from a method that uses a method as a parameter

I have a SQL template method that I want to return a string as well as a variety of methods that execute queries that I want to get the string from:

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();
}

Above is how I would think this is approached. THis would be the call:

string test = sqlQueryReturnString(getPKofUserLoggedIn);

THis part is not working:

result = sqlMethod(conn);

It appears sqlMethod is presumed void.

What do I do to get the functionality I want?

Upvotes: 1

Views: 77

Answers (1)

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174309

You want a Func<SqlConnection, string>. Action is for void methods, Func for methods that return something.

Upvotes: 5

Related Questions