As part of our refactoring of the persistence layer implemented with the Entity Framework, we developed an approach for some tricky problems. Although i just discuss one specific scenario, the following solution is probably useful for many different issues:
We are using some objects which won’t be deleted in the classic way by removing them from the underlying database table. Instead, we mark them as deleted, set the purge date and the user who initiated the action. The same procedure exists for creating and modifing objects. You surely can imagine why we are doing this. So how can we achieve this behaviour in a transparent, implicit manner.
Step 1: Set up some interfaces like IHaveCreationDate, IHavePurgeDate and IHaveModificationDate.
Step 2: Now it depends on your engineering strategy: Code First, Model First or Database First. According to your strategy you might using POCOs or you don’t. First of all, you can implement this solution in every single case, but you might change a little of the implementation. Here’s the way like we are using it with our POCOs (take a look at the ADO.NET Team Blog about the usage of POCOs) automatically generated by the EF:
Second part of the partial worker implementation in a separate file (don’t adapt the auto generated class!)
1:publicpartialclass worker : IHavePurgeDate
5: isDeleted = true;
6: purge_Date = DateTime.Now;
7: deleted_from = currentUser.ID;
If you use Code First engineering, you won’t need a seperate file – of course!
Step 3: Build your own context or extend the existing one
If you use the auto generated context of the EF, you will have to create one more partial class to extend this context. If you use you’re own implementation, you can add the following code directly to your class: