1

I have problem with field car_brand_id. I need this field to create relationship, but i have error in this string. How fix this problem?

string brand_query = "SELECT car_brand_id FROM car_brand WHERE name_brand = @brand ";
cmd = new SqlCommand(brand_query, SqlConn);
cmd.Parameters.AddWithValue("@brand", brand);
int car_brand_id = cmd.ExecuteNonQuery();  // There i have an error



string model_query = "INSERT INTO car_model (name_model, car_brand_id) VALUES (@model, @car_brand_id)";
cmd = new SqlCommand(model_query, SqlConn);
cmd.Parameters.AddWithValue("@model", model);
cmd.Parameters.AddWithValue("@car_brand_id", car_brand_id);
cmd.ExecuteNonQuery();

Error message:

The INSERT statement conflicted with the FOREIGN KEY constrains. "FK_car_model_car_b30F848ED". The conflict occured in db "avtoservice:, table "dbo.car_brand", column "car_brand_id". The statument has been terminated

8
  • 2
    Did you read the error message? Commented Jun 1, 2015 at 21:14
  • @SLaks The INSERT statement conflicted with the FOREIGN KEY constrains. "FK_car_model_car_b30F848ED". The conflict occured in db "avtoservice:, table "dbo.car_brand", column "car_brand_id". The statument has been terminated Commented Jun 1, 2015 at 21:20
  • Read the error message. Your database isn't letting you insert that data. Commented Jun 1, 2015 at 21:32
  • 1
    @RickHas please the error to the post, it can be edited)) Commented Jun 1, 2015 at 21:32
  • is your car_brand_id valid? Check your car_brand table data. Commented Jun 1, 2015 at 21:40

2 Answers 2

3

Try changing this line:

int car_brand_id = cmd.ExecuteNonQuery();  // There i have an error

To this:

int car_brand_id = (int)cmd.ExecuteScalar();

The ExecuteNonQuery() method will return the number of rows affected, not the value from your query, as it appears you are expecting.

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

3 Comments

Implicit conversion type " object " in the "INT" is impossible. There is a clear transformation ( possibly there is no reduction )
int car_brand_id = (int) cmd.ExecuteScalar();
Yes, you will need to cast it to int as @JaredMoore stated. I will fix the answer to reflect this.
1

Parameters should not be in quotes.

That's a string that literally says @brand, not the value of the parameter.

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.