Use either:
public bool SaveRecording(Recording recording)
{
// Load only the DateTime property, not the full entity
DateTime oldCreatedOn = db.Recordings
.Where(r => r.Id == recording.Id)
.Select(r => r.CreatedOn)
.SingleOrDefault();
recording.CreatedOn = oldCreatedOn;
db.Entry(recording).State = EntityState.Modified;
db.SaveChanges();
return true;
}
(Edit: The query only loads the CreatedOn
column from the database and is therefore cheaper and faster than loading the full entity. Because you only need the CreatedOn
property using Find
would be unnecessary overhead: You load all properties but need only one of them. In addition loading the full entity with Find
and then detach it afterwards could be shortcut by using AsNoTracking
: db.Recordings.AsNoTracking().SingleOrDefault(r => r.Id == recording.Id);
This loads the entity without attaching it, so you don't need to detach the entity. Using AsNoTracking
makes loading the entity faster as well.)
Edit 2
If you want to load more than one property from the database you can project into an anonymous type:
public bool SaveRecording(Recording recording)
{
// Load only the needed properties, not the full entity
var originalData = db.Recordings
.Where(r => r.Id == recording.Id)
.Select(r => new
{
CreatedOn = r.CreatedOn,
CreatedBy = r.CreatedBy
// perhaps more fields...
})
.SingleOrDefault();
recording.CreatedOn = originalData.CreatedOn;
recording.CreatedBy = originalData.CreatedBy;
// perhaps more...
db.Entry(recording).State = EntityState.Modified;
db.SaveChanges();
return true;
}
(End of Edit 2)
Or:
public bool SaveRecording(Recording recording)
{
Recording oldVersion = db.Recordings.Find(recording.Id);
recording.CreatedOn = oldVersion.CreatedOn;
// flag only properties as modified which did really change
db.Entry(oldVersion).CurrentValues.SetValues(recording);
db.SaveChanges();
return true;
}
(Edit: Using CurrentValues.SetValues
flags only properties as Modified which indeed have been changed compared to the original state in the database. When you call SaveChanges
EF will sent only the properties marked as modified in an UPDATE statement to the database. Whereas setting the state in Modified
flags all properties as modified, no matter if they really changed or not. The UPDATE statement will be more expensive because it contains an update for all columns.)