How do I get the entity framework to work with archive flags?

I'm trying to create a set of tables where we don't actually delete them, but rather we set the archive flags instead. When we delete an entity, it shouldn't be deleted, it should be marked as archived instead.

What are the programming patterns to support this?

I would also prefer not to have to roll out my own stored procs for every table that have these archive flags if there is another solution.

Answers


This is an old question and it doesn't specify the EntityFramework version. There are a few good solution for newer versions:

Entity Framework: Soft Deletes Are Easy

Soft Delete pattern for Entity Framework Code First

Entity Framework 5 Soft Delete

Also there are sources for EF 6.1.1+

Highlights of Rowan Miller’s EF6/EF7 Talk at TechEd 2014

Entity Framework: Building Applications with Entity Framework 6


myEntity.IsArchived = true;
context.SaveChanges();

if your requirements are to not delete, then don't delete ;-)


You'll have to write your own logic to do this, and steer clear of the "MarkForDeletion" method on those entities.

Your logic will need to take a provided entity, alter it in some way to signify it is now "archived", and then Save the changes on the context.

You'll then need to make sure any code pulling from the DB honors these values that signify an archived record.

To make it simpler, you can create partial classes to match your entity classes, so they honor say, a custom interface. That way you can code against the interface and not have to use reflection to set the entity values.

If you can use .NET 4.0, EF supports POCOs and you can mark the entities natively with the appropriate interfaces, which will cut down the number of files you have to work with.


I'm not sure about best practices, but you might try writing your own DeleteObject method and putting it in a class of some sort (EFHelper is the name of the class I use for these sorts of things). Then instead of calling ObjectContext.DeleteObject, you call EFHelper.DeleteObject, and do any custom logic you care to do in that method. If you're consistent with the way you name these archive flag properties, you can use .NET's reflection API to find the archive_flag property of each EntityObject you're "deleting" and set it appropriately.


Need Your Help

java.lang.NoClassDefFoundError: org/hibernate/boot/MetadataBuilder

java hibernate maven spring-mvc jpa

I have this strange error when deploying my application , but the jar needed is in my POM file !!!