[SalesForce] Unable to delete ContentDocumentLink

This is all on a Salesforce Community.

I have a situation where a user is uploading a file and it's temporarily assigned to their user record. Once they submit the form and it creates a custom object record, I need to re-assign those files to the new custom object record. This is not part of a trigger but a controller behind a custom lightning component.

Here's the code that's doing the work:

List<ContentDocumentLink> oldLinks = [select Id, ContentDocumentId, LinkedEntityId, ShareType from ContentDocumentLink where LinkedEntityId=:userId and ContentDocumentId=:ids];
List<ContentDocumentLink> newLinks = new List<ContentDocumentLink>();

for (ContentDocumentLink old : oldLinks) {
    newlinks.add(new ContentDocumentLink(ContentDocumentId=old.ContentDocumentId, LinkedEntityId=wrapper.objProject.Id, ShareType=old.ShareType));
}

delete oldLinks;
insert newLinks;

The resulting error is:

System.DmlException: Delete failed. First exception on row 0 with id 06Aq0000002COEuEAO; first error: FIELD_INTEGRITY_EXCEPTION, field integrity exception: []

I've now tried to bust this down to a super basic level to just:

List<ContentDocumentLink> toDelete = [select Id from ContentDocumentLink where Id='06Aq0000002COEuEAO'];

delete toDelete;

But I receive the same error. What I can't determine is why this is an issue. That is the only link that exists for that document.

Anyone have any ideas?

Best Answer

enter image description here

As you can see above, when you upload a file to any record like account New Test Account, it will always create 2 links - 1st for the user TestUser with share type I (which cannot be deleted) and 2nd for the record itself with share type V. Henceforth when you share the file with new objects, it will create new links of share type V. You cannot delete the primary link which is created for the owner user of file. This is standard file upload flow.

So, in your case you can just create new link and you should not try to delete the link for user.