Skip to content

DeleteService

Jon Smith edited this page Jun 23, 2015 · 4 revisions

Deleting a database item is fairly straightforward - You provide the primary key(s) of the entry you want to delete and it deletes it (if it can). However there are a few cases where the delete involves other subclasses (foreign keys) so GenericService has another command to help in those cases.

DeleteService (sync and async)

`Delete' deletes a data item from the database using its primary key(s). The commands are:

  • ISuccessOrErrors Delete<T>( param object [] keys) - sync
  • Task<ISuccessOrErrors> DeleteAsync<T>( param object [] keys) - async

The methods return a status (see Introduction to Commands, Feedback for explanation). If successful the property .IsValid is true and the property SuccessMessage has a confirmation message. If the property .IsValid is false then the List property Errors contains a list of errors. Typical errors are:

  • "Could not delete entry as it was not in the database. Could it have been deleted by someone else?"
  • A foreign key violation, i.e. you tried to delete something that another table row was pointing to. This gives the error "This operation failed because another data entry uses this entry."

DeleteWithRelationships (sync and async)

There are a very small number of cases where you need delete to do a bit more. They are rare but here are two I have come across.

  • In one database the deletion of a order line item required the total order value column on the lined sales order to be updated, which needed some extra code added.
  • You may want to do your own checking, or message, on whether this entry is really allowed to be deleted.
  • The database item you wish to delete may have relationships which needs deleting with this entry, but a cascade delete has not been set. This is rare (possibly a database design fault), but I have come across this.

The two commands are:

  • ISuccessOrErrors DeleteWithRelationships<TEntity>( Func<IGenericServicesDbContext, TEntity, ISuccessOrErrors> removeRelationships, params object[] key - sync
  • Task<ISuccessOrErrors> DeleteWithRelationshipsAsync<TEntity>( Func<IGenericServicesDbContext, TEntity, Task<ISuccessOrErrors>> removeRelationshipsAsync, params object[] key - async

The provided method for the removeRelationships (sync & async) parameter is called after the specified data entry is found but before that entry has been marked as deleted. On its call it is provided with two parameters:

  1. The DbContext of this call so it can access the database.
  2. The entry found for deletion.

In this method you can put whatever code you like. If the returned status .IsValid is true then it carries on with the deletion. If it is false it returns that status to the user.