使用 Entity Framework sql 将 Null 插入数据库

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();
}

错误

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

该字段似乎不可为空。它必须具有实际值。

根据文档(链接如下),当字符串参数为 null 时,Convert.ToInt32 returns 0。

因此,以下行将 MQCode 设置为 0,这是 MQCode 的无效外键值。

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

考虑改用以下内容:

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

这将 return 一个空值或一个整数。

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