更新行时出现并发冲突问题

时间:2011-04-16 10:27:50

标签: c# .net vb.net

T_MemTypeAdvanceBooking表包含以下列:

CentreID                Int               PrimaryKey
MembershipType          Uniqueindentifier PrimaryKey
FacilityName            UniqueIdentifier  PrimaryKey
ActivityName            NvarChar(35)      PrimaryKey
NumOfAdvanceDaysBooking smallint

我知道拥有这些主键可能听起来很愚蠢,但在我的应用程序中,当我填写所有键并进行插入时,它没关系!但是当我尝试使用不同的NumOfAdvancedDaysBooking值更新一行时,它会抛出ConcurrencyViolation的异常,那是怎么回事?在我的情况下,这有什么解决方法? 这里是更新命令:

Me.SqlUpdateCommand1.CommandText = "UPDATE [T_MemTypeAdvanceBooking] SET [CentreId" & _
    "] = @CentreId, [MembershipTypeId] = @MembershipTypeId, [MAIN FACILITY USED] = @M" & _
    "AIN_FACILITY_USED, [ActivityType] = @ActivityType, [NumOfAdvanceDays] = @NumOfAd" & _
    "vanceDays WHERE (([CentreId] = @Original_CentreId) AND ([MembershipTypeId] = @Or" & _
    "iginal_MembershipTypeId) AND" & _
    "([ActivityType] = @Original_ActivityType) AND ([RowVer] = @Original_RowVe" & _
    "r));"

1 个答案:

答案 0 :(得分:1)

删除RowVer条件:

Me.SqlUpdateCommand1.CommandText = "UPDATE [T_MemTypeAdvanceBooking] SET [CentreId" & _
    "] = @CentreId, [MembershipTypeId] = @MembershipTypeId, [MAIN FACILITY USED] = @M" & _
    "AIN_FACILITY_USED, [ActivityType] = @ActivityType, [NumOfAdvanceDays] = @NumOfAd" & _
    "vanceDays WHERE (([CentreId] = @Original_CentreId) AND ([MembershipTypeId] = @Or" & _
    "iginal_MembershipTypeId) AND" & _
    "([ActivityType] = @Original_ActivityType));"

说明:

在DataTable中更新DataRow时,实际上会获得2行。一个有DataRowVersion Current,另一个有Original。大多数情况下,您使用当前版本的DataRow。因此,当您发送更新的行时(通常通过DataAdapter),RowVersion不等于Original,而是Current。然后发生的是条件为假并且DB中没有记录更新。 DataAdapter获取没有记录更新的信息,并认为有人在您之前更新了记录并引发了并发异常。

我建议您在表格列上添加Integer类型的版本。插入时将Version设置为1.在每次后续更新中,将Version增加1.这样,您可以通过在发出DB UPDATE时将获取的Version值(@Original_Version)与实际版本值([Version])进行比较来检查乐观并发性。言。

Me.SqlUpdateCommand1.CommandText = "UPDATE [T_MemTypeAdvanceBooking] SET [CentreId" & _
    "] = @CentreId, [MembershipTypeId] = @MembershipTypeId, [MAIN FACILITY USED] = @M" & _
     "AIN_FACILITY_USED, [ActivityType] = @ActivityType, [NumOfAdvanceDays] = @NumOfAd" & _
    "vanceDays WHERE (([CentreId] = @Original_CentreId) AND ([MembershipTypeId] = @Or" & _
    "iginal_MembershipTypeId) AND" & _
    "([ActivityType] = @Original_ActivityType) AND  ([Version] = @Original_Version));"