user3340627
user3340627

Reputation: 3143

Update modified fields of an item only

My Car entity has the following properties:

Name,
Color, 
CreationDate

I'm using this code to update my Car item:

using (MyContextEntities db = new MyContextEntities())
{
     db.Entry(Car).State = EntityState.Modified;
     db.SaveChanges();
}

However, when the user only updates the Name and Color of my Car item, the item CreationDate turns to "0001/01/01".

How can I tell the EF to only update the modified fields and keep those that weren't modified as is?

Upvotes: 1

Views: 158

Answers (1)

Steve Greene
Steve Greene

Reputation: 12304

You could go:

using (MyContextEntities db = new MyContextEntities())
{
     db.Entry(Car).State = EntityState.Modified;
     db.Entry(model).Property(x => x.CreationDate).IsModified=false;
     db.SaveChanges();
}

Or you might consider using ViewModels that have only the properties you want to modify.

Upvotes: 1

Related Questions