1

I want to insert a query and I want to pass the logged in User ID as a parameter, the UserID is a string.

I tried to do this:

  SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=project;Integrated Security=true;");
            var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
            
            SqlCommand cmd = new SqlCommand("INSERT INTO Invoice VALUES (SYSDATETIME(),'@id',0)");
           cmd.Connection= con;
            con.Open();
            cmd.Parameters.Add("@id",userId);
            cmd.ExecuteNonQuery();
            con.Close();

I am getting an error on cmd.Parameters.Add("@id",userId); that the userId needs to be of the data type "SqlDbType". How could I pass this var?

1 Answer 1

1

You can't set the value directly when adding a parameter, and the Add overload that takes 2 parameters required the name of the parameter and it's type. You can either do this:

var p = cmd.Paramaters.Add("@id", SqlDbType.VarChar);
p.Value = userId;

Or:

cmd.Paramaters.Add("@id", SqlDbType.VarChar).Value = userId;

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.