Created
April 22, 2014 15:42
-
-
Save nozzlegear/11184132 to your computer and use it in GitHub Desktop.
Never update certain entity properties using Entity Framework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Open database context | |
using(DbContext db = new DbContext()) | |
{ | |
//Get the id of the entity we want to update | |
int id = 1; | |
//Create an instance of the entity we want to update | |
SomeEntity entity = new SomeEntity(){ | |
Id = id, | |
Email = "foo@bar.com", | |
Name = "Joshua Harms", | |
Birthday = "July 5th", | |
CreditCard = 4242424242424242 | |
}; | |
//Attach the entity to the context | |
db.YourDbSet.Attach(entity); | |
//Now set the entity's entire state to modifed | |
db.Entry(entity).State = System.Data.Entity.EntityState.Modified; | |
//We never ever want to update CreditCard property, so set its IsModified property to false | |
db.Entry(entity).Property(e => e.CreditCard).IsModified = false; | |
//Save the changes to the dbcontext | |
db.SaveChanges(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment