简体   繁体   中英

Insert Null into database with Entity Framework sql

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.

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://docs.microsoft.com/en-us/dotnet/api/system.convert.toint32?view=netframework-4.8#System_Convert_ToInt32_System_String_

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM