开发者

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

开发者 https://www.devze.com 2022-12-24 20:47 出处:网络
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 开发者_JAVA百科we delete an entity, it shouldn\'t be deleted, it should be

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 开发者_JAVA百科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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号