Отмена записи ошибки перехвата с помощью Forrenkey Bond - PullRequest
1 голос
/ 19 июня 2019

Я создаю веб-приложение для прихода на английском языке.Это веб-приложение CRUD, в котором я использую SQL Server.У меня есть страница product-list.component, где я создал метод OnDelete, чтобы иметь возможность удалить один продукт.Метод правильный, но у меня проблема в том, что в таблице есть связи с таблицей «CommandRighe», которые запрещают удаление.Я изменил метод OnDelete с помощью try catch, чтобы иметь возможность перехватить код ошибки и отправить сообщение об ошибке пользователю.Это не работает, и я хотел бы знать, как решить проблему, чтобы отправить пользователю сообщение об ошибке, сообщающее ему, что запись не может быть удалена.Как я могу сделать ?спасибо

Moreno

System.Data.Entity.Infrastructure.DbUpdateException non è stata gestita dal codice utente
  HResult=-2146233087
  Message=Errore durante l'aggiornamento delle voci. Per ulteriori dettagli, vedere l'eccezione interna.
  Source=EntityFramework
  StackTrace:
       in System.Data.Entity.Internal.InternalContext.SaveChanges()
       in System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
       in System.Data.Entity.DbContext.SaveChanges()
       in WebApiSif.Controllers.PRODOTTIController.DeletePRODOTTI(Int32 id) in I:\Angular Project\SifWork\WebApiSif\WebApiSif\Controllers\PRODOTTIController.cs:riga 162
       in lambda_method(Closure , Object , Object[] )
       in System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass6_2.<GetExecutor>b__2(Object instance, Object[] methodParameters)
       in System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
       in System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
  InnerException: 
       HResult=-2146233087
       Message=Errore durante l'aggiornamento delle voci. Per ulteriori dettagli, vedere l'eccezione interna.
       Source=EntityFramework
       StackTrace:
            in System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
            in System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<Update>b__2(UpdateTranslator ut)
            in System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func`2 updateFunction)
            in System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update()
            in System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35()
            in System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
            in System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction)
            in System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass2a.<SaveChangesInternal>b__27()
            in System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
            in System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction)
            in System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options)
            in System.Data.Entity.Internal.InternalContext.SaveChanges()
       InnerException: 
            Class=16
            ErrorCode=-2146232060
            HResult=-2146232060
            LineNumber=1
            Message=L'istruzione DELETE è in conflitto con il vincolo REFERENCE "FK_CommandaRighe_PRODOTTI". Il conflitto si è verificato nella tabella "dbo.CommandaRighe", column 'NProdotto' del database "SifDB".
L'istruzione è stata interrotta.
            Number=547
            Procedure=""
            Server=DESKTOP-P3TEF6K\SQLEXPRESS
            Source=.Net SqlClient Data Provider
            State=0
            StackTrace:
                 in System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
                 in System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
                 in System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
                 in System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
                 in System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
                 in System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
                 in System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
                 in System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
                 in System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
                 in System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext`1 c)
                 in System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
                 in System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
                 in System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
                 in System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues)
                 in System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
            InnerException: 


Message = The DELETE statement conflicts with the REFERENCE constraint "FK_CommandaRighe_PRODOTTI". The conflict occurred in the "dbo.CommandaRighe" table, column 'NProduct' of the "SifDB" database.
The instruction has been interrupted.

onDelete (id: номер) {

if (confirm('Confermi la cancellazione del Record ?')) {
      try {
          this.service.deleteProdotti(id).then(res => {       // this.service.deleteProdotti(id).subscribe(res => {
          this.service.refreshList();
          this.toastr.warning('Cancellazione eseguita con successo', Header_Msg);
        });
      } catch (error) {
        console.error('errore in cancellazione: ' + error);
    }



  }

}


-----------------------------------------

the overall class is as follows

import {Component, OnInit, SystemJsNgModuleLoader} from '@ angular / core';
import {Products} from 'src / app / model / prodotti.model';
import {ProductsListService} from 'src / app / features / products / components / products-list / products-list.service';
import {ToastrService} from 'ngx-toastr';


let Header_Msg = "Product Manager";


@Component ({
  selector: 'app-products-list',
  templateUrl: './products-list.component.html',
  styleUrls: ['./products-list.component.css']
})
export class ProductsListComponent implements OnInit {

  constructor (private service: ProductsListService, private toastr: ToastrService) {

   }

  ngOnInit () {
    this.service.refreshList ();
  }

  populateForm (emp: Products) {
    this.service.formData = Object.assign ({}, emp);
  }

  onDelete (id: number) {
if (confirm ('Confirm the deletion of the record?')) {
      try {
          this.service.deleteProducts (id) .then (res => {// this.service.deleteProdotti (id) .subscribe (res => {
          this.service.refreshList ();
          this.toastr.warning ('Successful deletion', Header_Msg);
        });
      } catch (error) {
        console.error ('error in deletion:' + error);
    }



  }

}

}`enter code here`
...