违反主键不插入对象 'dbo 中的重复键。事件类型"。重复的键值为 (6)

  • 本文关键字:类型 键值 事件 对象 插入 dbo c# asp.net
  • 更新时间 :
  • 英文 :


如果我有现有的 id,我想显示一个消息框,上面写着"ID 存在,插入不成功",但有此错误!

protected void Button1_Click(object sender, EventArgs e)
{
int result = 0;
EventType produ = new EventType(int.Parse(tb_id.Text), tb_Name.Text);
result = produ.EventTypeInsert();
if (produ == null)
{
if (result > 0)
{
Response.Write("<script>alert('Insert successful');</script>");
}
else
{
Response.Write("<script>alert('Insert NOT successful');</script>");
}
}
else
{
Response.Write("<script>alert('ID already exists.Insert NOT successful');</script>");
}
}

我认为你应该使用try catch block。捕获异常并根据异常提供所需的消息。

在您的情况下,我认为您的主键是自动增量的。因此,不要在该主键中传递值,因为数据库将自动递增该字段并将其插入。

注意:不要在主自动递增字段中传递值。

请注意,您在 produ 上检查 null 很奇怪。删除它或检查 produ != 空。你可以像下面这样做。请注意,您也可以将 try catch 放在 EventTypeInsert 函数中。我认为将导致更干净的代码。

int result = 0;
try
{
EventType produ = new EventType(int.Parse(tb_id.Text), tb_Name.Text);       
result = produ.EventTypeInsert();
if (result > 0)
{
Response.Write("<script>alert('Insert successful');</script>");
}
else
{
Response.Write("<script>alert('Insert NOT successful');</script>");
}
}
catch (SqlException ex)
{
Response.Write("<script>alert('ID probably already exists.Insert NOT successful');</script>");
}
catch (Exception ex)
{
// maybe log a general error
}

最新更新