Manually Seting a LINQ to SQL Entity's Timestamp

Suppose you want to manually persist your LINQ to SQL entities without an ObjectDataSource or LinqDataSource using the entities' timestamp column. You pick the timestamp, perhaps from an hidden field on your page, but you cannot change the System.Data.Linq.Binary property to another value, because the Binary won't allow it. You need to use reflection, here's how:

public void Update(Int32 key, String data, String timestamp)
  using (MyContext ctx = new MyContext())
    MyEntity entity = ctx.MyEntities.Where(e => e.Key = key).Single();
    entity.Data = data;
    this.SetTimestamp(entity.RowVersion, timestamp);
    ctx.SubmitChanges();	//will throw an ChangeConflictException if the timestamps are different

protected void SetTimestamp(Binary ts, String timestamp)
  bytesField.SetValue(ts, Convert.FromBase64String(timestamp.Replace("\"", String.Empty)));
  hashCodeField.SetValue(ts, null);
  computeHashMethod.Invoke(ts, null);

Bookmark and Share



Comments have been disabled for this content.