简体   繁体   中英

Updating foreign key on soft delete

I have 2 rows in my database. Category and Movie .

When I'm soft deleting Movie , I want to remove the FK reference to Category .

I have a delete method that looks like this:

        public override async Task DeleteAsync(long id, bool permanent = false)
        {
            await DbFactory.ExecAsync(async (db) =>
            {
                if (permanent)
                {

                    await db.DeleteAsync<Movie>(x => x.Id == id);
                }
                else
                {
                    await db.UpdateAsync<Movie>(new { Deleted = true, CategoryId = 0 }, x => x.Id == id);
                }
            });
        }

But it throws an FK exception when I'm trying to update the CategoryId

How can I do this? I want to be able to soft delete a Movie , and then only if the category doesn't have any references be able to remove the category.

Does an entry with CategoryId = 0 exist? It probably doesn't, which is why you're getting an error. You have two approaches here:

  1. Create a dummy "deleted" category, with Id = 0 (I personally prefer -1 for those things), update to it when softly deleting

  2. Set CategoryId to NULL , if the field allows NULLs . This means there's no relation to the category for this record.

If I were you, these would be the steps

  1. Check whether there are Any movies with the same category id, but with different id than the movie to be removed

  2. If so, then remove only the movie

  3. If not, then remove the Category and cascade (if not possible, then remove the movie first and then the category)

There is also a concurrency problem to handle. What if there are two movies of a category and they are removed at the same time? That could result in an issue that the movies are removed in different threads and both threads check whether there are any other movies and for each movie the other movie is found before it is removed. To cope with this situation, I propose to create a remove movie queue of some kind and when a movie is to be removed, it would enter the queue. This sequential manner of removing movies would fix the concurrency problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM