我的学习课程有点问题。 我需要一个基本的乐观并发实现 我从Microsoft文档中的示例代码开始,然后编写一个测试用例来检查Optimistic条件。 代码是这样的:
private void TestConcorrenza_Click(object sender, EventArgs e)
{
// Assumes connection is a valid SqlConnection.
SqlDataAdapter adapter = new SqlDataAdapter("SELECT Id,Nome FROM DAti ORDER BY Id",FirstConnection);
// The Update command checks for optimistic concurrency violations in the WHERE clause.
adapter.UpdateCommand = new SqlCommand("UPDATE Dati Set Id = @Id, Nome = @Nome WHERE Id = @oldId AND Nome= @oldNome", FirstConnection);
adapter.UpdateCommand.Parameters.Add( "@Id", SqlDbType.NChar, 5, "Id");
adapter.UpdateCommand.Parameters.Add("@Nome", SqlDbType.NVarChar, 30, "Nome");
// Pass the original values to the WHERE clause parameters.
SqlParameter parameter = adapter.UpdateCommand.Parameters.Add("@oldId", SqlDbType.NChar, 5, "Id");
parameter.SourceVersion = DataRowVersion.Original;
parameter = adapter.UpdateCommand.Parameters.Add("@oldNome", SqlDbType.NVarChar, 30, "Nome");
parameter.SourceVersion = DataRowVersion.Original;
// Add the RowUpdated event handler.
adapter.RowUpdated += new SqlRowUpdatedEventHandler(OnRowUpdated);
DataSet dataSet = new DataSet();
adapter.Fill(dataSet, "Dati");
// Modify the DataSet contents.
Update_for_Test();
adapter.Update(dataSet, "Dati");
foreach (DataRow dataRow in dataSet.Tables["Dati"].Rows)
{
if (dataRow.HasErrors)
Console.WriteLine(dataRow [0] + "\n" + dataRow.RowError);
}
DataTable aTable = new DataTable();
adapter.Fill(aTable);
this.Test1.DataSource = aTable;
}
protected static void OnRowUpdated(object sender, SqlRowUpdatedEventArgs args)
{
if (args.RecordsAffected == 0)
{
args.Row.RowError = "Optimistic Concurrency Violation Encountered";
args.Status = UpdateStatus.SkipCurrentRow;
}
}
这是主要部分,这是测试用例:
public void Update_for_Test()
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT Id,Nome FROM
Dati ORDER BY Id", SecondConnection);
SqlDataAdapter ada= new SqlDataAdapter("UPDATE Dati SET Nome 'Anna' WHERE Nome='Luca'", SecondConnection);
DataSet dataSet = new DataSet();
ada.Fill(dataSet, "Dati");
adapter.Fill(dataSet, "Dati");
DataTable aTable = new DataTable();
adapter.Fill(aTable);
this.Test2.DataSource = aTable;
}
我不明白为什么foreach中的情况是错误的。 有人有想法吗? 好多了,干得好。