Skip to content
Jon P Smith edited this page Apr 11, 2018 · 3 revisions

Sometimes you want to delete an entity, and there are two methods to do that. But before I describe that I do need to say that EF Core has a way to soft delete something - i.e. it set a flag to say the entity shouldn't appear in a normal query. See this Microsoft's documentation on Global query filters.

CrudServices has two versions of the Delete command - a simple delete, and one where you can interact with the entity before it is deleted. It turns out in (many) cases a simple delete isn't good enough, either because if you delete it will throw an exception unless you do something, or because you need to check something and provide a more friendly error message.

I'll start with the simple version, but you most likely want the DeleteWithActionAndSave.

DeleteAndSave<TEntity>(params object[] keys)

You need to provide an entity type (it won't work with a DTO) and the primary key value(s) to delete the row. It checks it exists (friendly error message if not there) and then deletes it.

DeleteWithActionAndSave<TEntity>(Func<DbContext, TEntity, IStatusGeneric> runBeforeDelete, params object[] keys)

This version goes through the following stages

  1. It checks it exists (friendly error message if not there)
  2. It then calls your function, which has access to the DbContext and the entity you want to delete. You can run whatever tests you want, or add other entities to delete. If you think the delete is going to fail, or you want it to fail, then you add an error to the status and return it. You can also set a more useful success Message is you want to (I did this in the Authors/Delete.cshtml.cs version.
  3. If your function returns a status where IsValid is true then the found entity will be deleted.

Clone this wiki locally