Configuring non-timestamp tokens through data annotation

The data annotation configuration is straightforward; we have already seen the annotation in the Introducing concurrency tokens section of this chapter and it is not something new to us. Let's see how the ConcurrencyCheck attribute is configured:

    public class Post
{
// Code removed for brevity
[ConcurrencyCheck]
public string Url { get; set; }
// Code removed for brevity
}

The preceding configuration will let EF Core consider the Url column as the concurrency check column, and any further update to this column will restrict users from performing parallel updates.

We have already seen the concurrency conflicts while trying to edit posts in different tabs, which is kind of a simulation of a real-time concurrency conflict. Since we have handled the concurrency, let's now see how it stops the user from persisting values into the data store.

The post highlighted in the following screenshot will have a Url value of test-1, and if the value is changed, then any other new persistence will be rejected by the framework:

Again, we were following the same simulation of having two tabs of the same blog Edit page; the first tab updates the post data with the same URL, which will allow the persistence. The following screenshot is the data populated and updated from the first user:

If the second tab retains the Url value, EF Core will persist the updated post data into the data store:

We can see from the following screenshot that the Url value is unchanged. This ensures that the record we were searching for of an update exists, thereby allowing EF to persist the entity:

The second tab will try to change the Url value, which causes EF Core to stop the persistence of post data into the data store, which throws the error Database operation expected to affect 1 row(s) but actually affected 0 row(s):

We can see that the error is thrown as explained, which says that the records don't exist anymore, which is supposed to update one row(s):

There is an internal operation carried out by EF to finalize whether the update is valid or not; that's the reason it says 1 row(s) is expected but 0 row(s) affected.

EF will translate the update into an SQL query that will contain the where clause, including the identity column and the concurrency check column. If the value is changed, then obviously no record would be available for the update operation (which was supposed to exist), and that's the reason it simply responds back saying it expected 1 row(s) to be updated but 0 row(s) were affected.

We have seen how non-timestamp concurrency works, along with annotation configuration. In the next section, let's see how the same concurrency token could be configured through Fluent API.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset