Q:

SQL Query throws error "failed to convert parameter value from a Guid to String'

I'm trying to get the UserName and put it in TempData but I get an error when the code reaches the ExecuteReader() method.
Here's my query code:
var InvoiceId = TempData["newinvoice"];
TempData["invoiceid"] = InvoiceId;
var UserID = TempData["UserID"];

string connection = "Data Source=.;Initial Catalog=project;Integrated Security=true;";

using (SqlConnection sqlconn = new SqlConnection(connection))
{
    using (SqlCommand sqlcomm = new SqlCommand("SELECT UserName FROM AspNetUsers WHERE Id = @id"))
    {
        sqlcomm.Parameters.Add("@id", SqlDbType.VarChar).Value = UserID;

        using (SqlDataAdapter sda = new SqlDataAdapter())
        {
            sqlcomm.Connection = sqlconn;
            sqlconn.Open();

            sda.SelectCommand = sqlcomm;

            SqlDataReader sdr = sqlcomm.ExecuteReader();

            while (sdr.Read())
            {
                TempData["UserId"] = sdr["UserName"];
            }
        }
    }
}

The User Id from TempData["UserID"] is an nvarchar(450) not an integer. I have no clue why that exception is happening - any help?
Note: here's an example from one of my user ids:
'aa776084-053e-452c-8b0d-b445cdbf457d'

A:

It looks like your id is a uniqueidentifier and if so I would recommend changing your database and code to use GUIDs.
However to fix your problem, you should be able to pass in the UserId and call toString() (as the value is most likely an object) e.g:
sqlcomm.Parameters.Add("@id", SqlDbType.NVarChar, UserID.ToString());

If you're only going to return one results, maybe use ExecuteScalar()
    using (SqlConnection sqlconn = new SqlConnection(connection))
    {
        using (SqlCommand sqlcomm = new SqlCommand("SELECT TOP 1 UserName from AspNetUsers where Id=@id", sqlconn)
        {
            sqlcomm.Parameters.Add("@id", SqlDbType.NVarChar, UserID.ToString());
            object result = sqlcomm.ExecuteScalar();
            if (result != null)
            {
                TempData["UserId"] = result.ToString(); // It looks like you're mixing UserId & UserName .
            }
        }
    }

