Soft delete with entity framework core p2 - using repository
In part 1 you’ve already known how soft delete works, but querying with db context directly make the code duplicate alot. By combining with repository (repo), your code will be shorter and clearer. Let’s see how it works in this post.
This post might a bit advance for you as it requires you to have deep knowledge about EF (Core). But don’t worry, I’ll make it easy and translate into Vietnamese soon (LOL)
First of all…
…you might not know how to update just few properties of an entity. Yes, you might not know. Let’s check:
Here I have 2 methods, UpdateAsync
and UpdateAllAsync
. The 2nd method works well as expected, but I have to pull all data from db. I expect that UpdateAsync
updates Description
only but it does not. As it’s new, I must set it as dirty by modifying the state, EF Core marks all properties dirty then update them all:
So how can I update just few properties?
It’s easy, instead of set whole entity dirty, I just set few properties dirty. Let’s see a simple version of my repository:
The line 18 table.Attach(entity);
has an important role here. After attached, all properties are set as UnChanged
, and then we modify given properties on demand.
And use it easily:
See the line 15? I tell repository to update just Description, and we have the output log as expected:
Soft delete is just DeletedAt update
Yes, so far we’ve known how to update just few properties. Then soft delete is just update DeletedAt. So let’s modify our repository a little bit:
Just a case, what if I really want to delete it? No problem:
It works the same way update does, let’s see:
and the log is:
What’s next?
So far so good. We have a repository to perform update just some properties and soft delete entity without touching the db first.
Our repository is quite good but not perfect yet. Some issues we may encounter:
- We might use tracking behaviour (
QueryTrackingBehavior.TrackAll
) thus attaching entity already in dbset will cause exception. - How to check if an entity is deleted, still living or none exist.
- How to restore an archived entity.
These things will be discussed in part 3. If you’re still confused this part, I highly recommend you to take an action now, do it and test it yourself, or…check the sample code here.
P/S: I still open for someone who wants to translate my posts into Vietnamese, you’ll have chance to improve your skill under my mentor. Hit F12 for my contacts.