-
Notifications
You must be signed in to change notification settings - Fork 97
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.
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
DbContextand 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
IsValidis true then the found entity will be deleted.