views:

49

answers:

1

I am developing application that works with sql server, I read and update data from (by) multiple sources.

Because of that, there is a problem that one updates already updated data....

How can I deal with that issue? (I know EF has built in Concurrency mode but if I understand right, if my design creates and disposes contextobject every time this won't work)

+2  A: 

The secret is normally to use a timestamp field and check that against the value in your object before you commit to the db. There's an article about this subject here.

Lazarus
this article talks about Concurrency mode, bust as i noted I think it won't work if recreate my context object
shivesh
By setting the concurrency mode on your timestamp to fixed it will mean that it requires the timestamp to be unchanged, even when you attach your incoming data to the context. If the timestamp then doesn't match the timestamp you are providing (previously retrieved in your earlier context session) then the update will fail as the record has changed. That seems to me what the article is saying.
Lazarus
As I understand this will work only if i keep same context object for all my database operations, but if I create new context object every time like: using (var context = new EntityContext()), it won't work. or is it?
shivesh
Not that's not true, the timestamp is a read-only SQL field that is updated by the SQL Server when you update the record. By setting it to fixed you'll indicate to EF that it shouldn't change, if it has then you know the underlying db record has changed. Concurrency support fails the update.
Lazarus
It's probably worth adding that even if EF fails to catch the concurrency violation, SQL Server will return an error if you tried to update a record with one containing a different timestamp.
Lazarus
lets say I have table with 2 columns: name, and age. So need to add another column: Timestamp and in the EF model I set it as fixed?
shivesh
Yes, that's right. The timestamp is in effect a read-only field (it's updated by the DB engine) so you can't actually write to it directly. It'll be updated every time you modify that record.
Lazarus
What do you mean it's read only? what makes it read only, timestamp datatype?
shivesh
Yes, it's read-only in the database, you cannot update it directly yourself.
Lazarus