无法更新标识列'LocationID'

Mar*_*ark 3 .net c# sql

我正在尝试更新ID值.因此,如果ID为1,则新值为2,则应使用新值替换旧ID.

后端:

     public static void UpdateLocation( int locationID, SqlConnection connection,                SqlTransaction transaction )
    {
        StringBuilder sqlString = new StringBuilder();
        SqlCommand command;

        sqlString.Append( "UPDATE [Location] SET " );
        sqlString.Append( "description = @description " );
        sqlString.Append( "WHERE locationID = @locationID " );
        command = new SqlCommand( sqlString.ToString(), connection );
        if( ( transaction != null ) ) command.Transaction = transaction;

        command.Parameters.Add( "@locationID", SqlDbType.Int ).Value = locationID;
       command.Parameters.Add( "@description", SqlDbType.VarChar ).Value = description;
        int rowsAffected = command.ExecuteNonQuery();

        if( !( rowsAffected == 1 ) )
        {
            throw new Exception( "An error has occurred while updating UpdateMedicationDispenseStatus." );
        }
    }
Run Code Online (Sandbox Code Playgroud)

前端:

      private void btnFromLocation_Click( object sender, System.Windows.RoutedEventArgs e )
     {
         if( !( ( Locations )cmbLocationDescriptionList.SelectedItem == ( Locations )cmbDescriptionListTo.SelectedItem ) )
         {


             for( int i = 0; i < lstMedicationForCurrentLocation.SelectedItems.Count; i++ )
    {
                 location = (Locations)cmbDescriptionListTo.SelectedItem;
        LocationData.UpdateLocation( location.LocationID );
Run Code Online (Sandbox Code Playgroud)

编辑我已经向SQL查询添加了一个参数,但仍然没有更新

R.C*_*R.C 6

以下解决方法可能不是优选的,但至少从知识角度来看,这可能对您有所帮助.

如果您想自己设置Identity列(LocationID)值而不是让Sql服务器执行,那么有一些解决方法.

set identity_insert Table_Name ON
Run Code Online (Sandbox Code Playgroud)

然后删除您的行并使用不同的标识重新插入它.请注意,您仍然无法将同一行更新为新标识.这将允许insert语句指定Identity列值.

完成具有新标识值的插入后,请identity_insert关闭

set identity_insert Table_Name OFF
Run Code Online (Sandbox Code Playgroud)

由于您是以编程方式进行更新,因此可以使用所有列的值,并且可能为除了您选择的标识值之外的所有列插入具有相同值的新行.