3

I'm trying to implement optimistic concurrency checking. I make use of the generic repository and unit of work patterns.

I have introduced a Timestamp-attributed property (as byte array) to my entity, which increases the value automatically whenever I update data (seems to be database managed, which is what it should do).

I load the updated values from a view model by mapping the VM to the actual model (using automapper). This results in a new (detached?) instance of an entity of the correct type with all the according fields set (including the timestamp).

The update itself is performed like

i_oOldEntity =  m_oDbSet.Find(i_oEntity.MaterialId)
context.Entry(i_oOldEntity).CurrentValues.SetValues(i_oEntity)
context.SaveChanges()

with i_oEntity being the automapped entity.

This updates the values itself fine, however it completely ignores the timestamp-value coming from the viewmodel. The resulting SQL code uses the latest rowversion value in the WHERE clause.

In short: how do I get my viewmodel-timestamp values to be used in the WHERE clause from EF?

urbanhusky
  • 43
  • 6

2 Answers2

0

Assuming:

var target = dbContext.Employees.Find(dto.Id);

This technique causes EF5 to use the dto's Timestamp value in the where clause when updating, and will trigger optimistic concurrency exception if dto's Timestamp does not match the database's Timestamp value:

context.Entry(target).Property(o => o.Timestamp).OriginalValue = dto.Timestamp;
context.Entry(target).Property(o => o.Timestamp).IsModified = true;

Updating OriginalValue alone does not do anything in EF5.

Jeremy Cook
  • 20,840
  • 9
  • 71
  • 77
-2

please update OriginalValues->RowVersion and you will get to paradise =)

P.J
  • 6,547
  • 9
  • 44
  • 74
Sasha
  • 1