When soft delete meets joint primary key

Most of the data is soft deleted, and sometimes it is a headache when encountering a joint primary key, such as

public class Thumbup
{
public int Id {get;set;}
public int UserId {get;set;}
public int BlogId {get;set;}
public bool IsDeleted {get;set;}
}

In this like table, each person can only like once, so the unique constraint is implemented through the joint primary key (UserId, BlogId). However, after soft deletion, when you like it again, the data cannot be inserted because the uniqueness constraint is violated. To solve this problem, the first idea is to change IsDeleted to

public DateTimeOffSet DaletedAt {get;set;}

Then modify the joint primary key to include DaletedAt, so that new data cannot be inserted after soft deletion. But in this case, the index has also become more complex, which should lead to a decrease in the efficiency of operating the data, so is there a better solution? I asked Google about foreign affairs. Sure enough, many people have encountered this problem. Some people have changed the IsDeleted field to public Guid DeletedToken {get;set;} to use non-repeated Guid to achieve it. It is also an idea, but the problem remains.

There is a better solution, but it requires database support, that is, conditional unique index, which means adding a condition to the index, pseudo code: Create Index on (UserId & BlogId) where IsDeleted == false 

The mongodb currently used has a partial index, and other databases will be updated when they are encountered.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325253161&siteId=291194637