Nate
Nate

Reputation: 5407

How do I prevent an object from being persisted using Entity Framework Code First?

I've an object model I'm persisting to a SQL Compact database using EF 4.2. One of my classes has a flag I use to determine if the object was modified. If the object was never changed from its default value I do not wish to save it to the database. Is there a way I can configure DbModelBuilder to toss out objects based on this property (it's a bool)? The other option I am considering is overriding DbContext.SaveChanges and just removing the object from the DbSet if the object was not modified. Suggestions?

Upvotes: 0

Views: 308

Answers (2)

Didaxis
Didaxis

Reputation: 8746

Why not add this to your business logic? What I mean is, why should EF deal with this? It could be as simple as:

if myObj.WasModified
    context.SaveChanges()

else
    do nothing

Not to mention EF won't do anything if the object wasn't modified anyway

Upvotes: 0

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364329

If the attached object was not modified it will not be saved to database. DbContext has its own change tracking mechanism and it will not use your custom property.

Upvotes: 2

Related Questions