-
Notifications
You must be signed in to change notification settings - Fork 95
Delete
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
.
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.
NOTE: This delete will not find entities hidden by Query Filters.
DeleteWithActionAndSave<TEntity>(Func<DbContext, TEntity, IStatusGeneric> runBeforeDelete, params object[] keys)
This version goes through the following stages
- It checks it exists (friendly error message if not there)
- 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. - If your function returns a status where
IsValid
is true then the found entity will be deleted.
WARNING: DeleteWithActionAndSave
turns off Query Filters.
This delete method uses a the query that includes IgnoreQueryFilter
at the start of the query to find entity to be deleted (see Microsoft docs on query filters). This is done so that if you have soft deleted an item you can still delete it.
The danger is if you are using query filters for multi-tenant use, which means you could inadvertently (or maliciously) delete an entity in another multi-tenant system. In multi-tenant systems I advise using the DeleteWithActionAndSave
and adding a check that the multi-tenant filter value is the same as the current tenant.