在我的项目中,我用两个数据集填充两个数据库表。我用来填充这些数据库表的方法如下所示:
SqlCommand sqlCommand = new SqlCommand();
SqlCommand command;
using (SqlConnection conn = new SqlConnection(strConn))
{
using (SqlCommand cmd = new SqlCommand(strQuery, conn))
{
using (SqlCommand cmdReset = new SqlCommand("DBCC CHECKIDENT('Doctor', RESEED, 0)", conn))
{
using (SqlCommand cmdUnCheck = new SqlCommand("alter table [dbo].[Doctor] nocheck constraint all",conn))
{
using (SqlCommand cmdCheck = new SqlCommand("alter table [dbo].[Doctor] with check check constraint all",conn))
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
conn.Open();
SqlTransaction sqlTransaction = conn.BeginTransaction();
cmd.Transaction = sqlTransaction;
cmdReset.Transaction = sqlTransaction;
cmdUnCheck.Transaction = sqlTransaction;
cmdCheck.Transaction = sqlTransaction;
try
{
cmdUnCheck.ExecuteNonQuery();
/*ERROR*/ cmd.ExecuteNonQuery();
cmdReset.ExecuteNonQuery();//deleting database table data
foreach (DataRow dr in ds.Tables[0].Rows) //Inserting new data into the Database table
{
command = new SqlCommand(query.createDoctorRow("Doctor",
dr[1].ToString(), dr[2].ToString(), Convert.ToInt64(dr[3]), Convert.ToInt32(dr[4])), conn, sqlTransaction);
command.ExecuteNonQuery();
}
cmdCheck.ExecuteNonQuery();
sqlTransaction.Commit();
conn.Close();
}
catch (Exception e)
{
sqlTransaction.Rollback();
throw;
}
}
}
}
}
}
上面的代码工作正常,直到第二个数据库表为空,但是当我在其中插入一些数据然后运行代码时,VS 显示错误 -->
DELETE 语句与 REFERENCE 约束“FK_Dr_ID”冲突。冲突发生在数据库“医院”、表“dbo.Patient”、列“Doctor_ID”中。该语句已终止。
这似乎很清楚,外键限制了查询的发生,但是由于我是初学者并且不知道该怎么做,所以我请求您的帮助..
在上面的代码中,我参考这个SO 答案进行了更改,但并不高兴,错误仍然存在于同一点。
可选:有没有办法减少using
我的代码中的语句?