无法将值NULL插入列'ID',表中

时间:2016-07-20 09:42:39

标签: c# sql asp.net sql-server visual-studio-2015

我的主表和外键为ID,主键id来自LeaveCategory,外键= LeaveCategoryId。但是我得到了这个错误:

  

无法将值NULL插入列'ID',表'dbo.Action';列不允许空值。 INSERT失败

但我真的不知道如何解决这个问题。

这是我的错误:

click image

这是代码:

public partial class AddLeaveType : System.Web.UI.Page
{
    int id = 0;

    SqlConnection conn = null;
    SqlCommand cmd = null;

    string connectionString = null;

    protected void Page_Load(object sender, EventArgs e)
    {
            if (!IsPostBack)
            {
                SqlDataReader dr = null;

                connectionString = ConfigurationManager.ConnectionStrings["LeaveManagementCS"].ConnectionString;

                conn = new SqlConnection(connectionString);

                string sql = "SELECT * FROM LeaveCategory";

                try
                {
                    cmd = new SqlCommand(sql, conn);

                    conn.Open();

                    dr = cmd.ExecuteReader();

                    while(dr.Read())
                    {
                        ListItem item = new ListItem(dr["Category"].ToString(), dr["Id"].ToString());
                        ddlCategory.Items.Add(item);
                    }

                    dr.Close();
                }
                catch (Exception ex)
                {
                    lblOutput.Text = "Error Message: " + ex.Message;
                }
                finally
                {
                    if (conn != null)
                        conn.Close();
                }
            }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        connectionString = ConfigurationManager.ConnectionStrings["LeaveManagementCS"].ConnectionString;

        conn = new SqlConnection(connectionString);

        string sql = "INSERT INTO LeaveType (Type, Description, NumOfDays) ";
        sql += "VALUES (@type, @desc, @nod)";

        try
        {
                cmd = new SqlCommand(sql, conn);

                cmd.Parameters.AddWithValue("@type", tbType.Text);
                cmd.Parameters.AddWithValue("@desc", tbDesc.Text);
                cmd.Parameters.AddWithValue("@nod", tbNod.Text);

                conn.Open();

                int rows = cmd.ExecuteNonQuery();

                if (rows > 0)
                {
                    lblOutput.Text = "Added successfully";
                }
        }
        catch (Exception ex)
        {
            lblOutput.Text = "Error Message:" + ex.Message;
        }
        finally
        {
            if (conn != null)
                conn.Close();
        }
    }
}

正确输出:

click image

3 个答案:

答案 0 :(得分:3)

PRIMARY KEY不能为空。它是唯一标识您的记录的字段。如果您没有为ID字段提供值,那么您将与PRIMARY KEY的基础概念发生冲突。

如果您不知道分配给ID字段的值是什么,那么您只需使用IDENTITY选项标记该列,并让Sql Server为您计算下一个值UNIQUE。

之后,如果您想知道为ID列分配了什么值,您可以简单地将代码更改为

protected void btnSubmit_Click(object sender, EventArgs e)
{
    connectionString = ConfigurationManager.ConnectionStrings["LeaveManagementCS"].ConnectionString;

    conn = new SqlConnection(connectionString);

    string sql = "INSERT INTO LeaveType (Type, Description, NumOfDays) ";
    sql += "VALUES (@type, @desc, @nod);"; // Note the semicolon in query here
    sql += "SELECT SCOPE_IDENTITY()";

    try
    {
        cmd = new SqlCommand(sql, conn);

        cmd.Parameters.AddWithValue("@type", tbType.Text);
        cmd.Parameters.AddWithValue("@desc", tbDesc.Text);
        cmd.Parameters.AddWithValue("@nod", tbNod.Text);

        conn.Open();

        int newID = Convert.ToInt32(cmd.ExecuteScalar());
        if (newID > 0)
        {
            lblOutput.Text = "Added successfully";
        }

    }
    catch (Exception ex)
    {
        lblOutput.Text = "Error Message:" + ex.Message;
    }
    finally
    {
        if (conn != null)
            conn.Close();
    }
}

顺便说一句,如果您在表格中添加了一个FOREIGN KEY,那么您还需要为该字段赋值。字段LeaveCategoryId似乎是LeaveCategory表的外键。如果这是真的,那么你应该从一些输入数据中给字段赋值。

作为旁注,似乎您正在使用全局连接对象。建议不要这样做,您应该创建一个本地连接对象,使用它然后尽快处置。 See Using Statement

答案 1 :(得分:0)

由于表'dbo.Action'中的列'ID'是主键(UNIQUE)。它不允许任何NULL值。因此在插入该表时'dbo.Action'使用任何样本整数或设置IDENTITY特定字段(因此它将自动获得增量)

答案 2 :(得分:0)

在Visual Studio中,单击视图>服务器资源管理器>右键单击表>打开表定义>右键单击“ ID”,然后单击属性>将“身份规范”的值从False更改为True>完成

相关问题