0

I am making a a WindowsFormsApp and I have to get by a ComboBox, idCategory that is the primary key of Table Category. The thing is this is a foreign key in Table Contract and I don't know how to make the query in C# since it looks is a different way.

cmdContract.CommandText = "Insert into Contract(idCategory, ContractNumber) VALUES" +
"((Select idCategory from  Category where idCategory=" + idCategory + "),@ContractNumber");

I have another table that doesn't have foreign keys and works good, but with this one, Contract, it doesn't insert anything

  • [What are good ways to prevent SQL injection?](https://stackoverflow.com/questions/14376473/what-are-good-ways-to-prevent-sql-injection) | [SqlCommand Parameters Add vs. AddWithValue](https://stackoverflow.com/questions/21110001/sqlcommand-parameters-add-vs-addwithvalue) –  Jun 15 '21 at 12:17

1 Answers1

0

If you know CategoryId and you are sure that a record with this CategoryId exists in DB, your query has to look like this: Insert into Contract(idCategory, ContractNumber) VALUES (@idCategory, @ContractNumber) (without inner select statement).

And one more advice: don't concatenate string for building a query, use the command with parameters (example)