我正在尝试在我的表“测验”中插入一些行。当我的表为空并且我尝试插入第一行时它可以工作,但是每当我尝试输入第二行时,我都会收到此错误:
Violation of UNIQUE KEY constraint 'UQ__Quiz__D0C4726C5B2346B6'. Cannot insert duplicate key in object 'dbo.Quiz'. The duplicate key value is (<NULL>).
我真的不知道是什么原因造成的,因为我总是为每一行输入不同的 ID。
表示层:
if (IsValidData())
{
quiz.QuizID = Convert.ToInt32(quizIDTextBox.Text);
quiz.QuizNaam = quizNaamTextBox.Text;
quiz.QuizDatum = Convert.ToString(quizDatumDateTimePicker.Text);
quiz.Locatie = locatieTextBox.Text;
quiz.Type = typeTextBox.Text;
quiz.Moeilijkheidsgraad = moeilijkheidsgraadTextBox.Text;
QuizDB.InsertQuiz(quiz);
MessageBox.Show("Quiz Toegevoegd", "Quiz");
}
数据库层:
public static void InsertQuiz(Quiz quiz)
{
string insertStatement = "INSERT INTO Quiz (QuizID,QuizNaam,QuizDatum,Locatie,Type,Moeilijkheidsgraad) VALUES (@QuizID,@QuizNaam, @QuizDatum, @Locatie, @Type, @Moeilijkheidsgraad)";
SqlCommand quizCommand = new SqlCommand(insertStatement, conn);
quizCommand.Parameters.Clear();
quizCommand.Parameters.AddWithValue("@QuizID", quiz.QuizID);
quizCommand.Parameters.AddWithValue("@QuizNaam", quiz.QuizNaam);
quizCommand.Parameters.AddWithValue("@QuizDatum", quiz.QuizDatum);
quizCommand.Parameters.AddWithValue("@Locatie", quiz.Locatie);
quizCommand.Parameters.AddWithValue("@Type", quiz.Type);
quizCommand.Parameters.AddWithValue("@Moeilijkheidsgraad",quiz.Moeilijkheidsgraad);
try
{
conn.Open();
quizCommand.ExecuteNonQuery();
}
catch (SqlException ex)
{
throw ex;
}
finally
{
conn.Close();
}
}
业务层:
public class Quiz
{
private int cQuizId;
private string cQuizNaam;
private string cQuizDatum;
private int cWinnaarId;
private string cLocatie;
private string cType;
private string cMoeilijkheidsgraad;
public Quiz() { }
public int QuizID
{
get { return cQuizId;}
set { cQuizId = value; }
}
public string QuizNaam
{
get { return cQuizNaam; }
set { cQuizNaam = value; }
}
public string QuizDatum
{
get { return cQuizDatum; }
set { cQuizDatum = value; }
}
public int WinnaarId
{
get { return cWinnaarId; }
set { cWinnaarId = value; }
}
public string Locatie
{
get { return cLocatie; }
set { cLocatie = value; }
}
public string Type
{
get { return cType; }
set { cType = value; }
}
public string Moeilijkheidsgraad
{
get { return cMoeilijkheidsgraad; }
set { cMoeilijkheidsgraad = value; }
}
}