0
private void BtnAdd_Click(object sender, EventArgs e)
{
    Model.Item items = new Model.Item
    {
        Code = Convert.ToInt32(txtCode.Text),
        Name = txtName.Text,
        MQCode = Convert.ToInt32(string.IsNullOrEmpty(txtMinmumQuantityNo.Text) ? null :   txtMinmumQuantityNo.Text)
    };
    db.Items.Add(items);
    db.SaveChanges();
}

Error

SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Items_MQ". The conflict occurred in database "C:\USERS\20101\DESKTOP\SIGMA V1\SIGMA V1\BIN\DEBUG\SIGMA.MDF", table "dbo.MQ", column 'MQCode'. The statement has been terminated.

4
  • 1
    You're not inserting NULL. Convert.ToInt32 converts null to 0. 0 isn't matching a record in the parent table. Commented Oct 23, 2019 at 16:37
  • Check the constraints on your foreign keys, some are not allowed to be null, some have to be unique. We cannot even see the type of MQCode here. Commented Oct 23, 2019 at 16:41
  • What can I use instead of Convert.ToInt32 And gives the result = null ?? Commented Oct 23, 2019 at 16:44
  • public Nullable<int> MQCode { get; set; } Commented Oct 23, 2019 at 16:46

2 Answers 2

1

According to the documentation (linked below), Convert.ToInt32 returns 0 when the string parameter is null.

As such, the following line is setting MQCode to 0 which is an invalid Foreign Key value for MQCode.

MQCode = Convert.ToInt32(string.IsNullOrEmpty(txtMinmumQuantityNo.Text) ? null :   txtMinmumQuantityNo.Text)

Consider instead using the following:

MQCode = string.IsNullOrEmpty(txtMinmumQuantityNo.Text) ? (int?)null : Convert.ToInt32(txtMinmumQuantityNo.Text)

This will either return a null or an integer.

https://learn.microsoft.com/en-us/dotnet/api/system.convert.toint32?view=netframework-4.8#System_Convert_ToInt32_System_String_

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

Comments

0

It looks like that field is not nullable. It must have an actual value.

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.