简体   繁体   中英

How to implement optimistic concurrency on navigation properties in Entity Framework 6 Database First

What's the idiomatic way to implement optimistic concurrency in Entity Framework Database First if you have navigation properties on your entities (Ie x to Many relationship between parent and child tables)? Do you need to check the rowversion on both parent and child entities or is there wa such that only checking the parent entity's rowversion would suffice to know whether any child table was updated as well as any parent?

Consider 2 tables:

Table Parent {
   ParentId INT PRIMARY KEY,
   ValueParent INT
   Version ROWVERSION
}


Table Child {
   ParentId INT FOREIGN KEY
   ChildId INT,
   ValueChild INT
   Version ROWVERSION
  (ParentId,ChildId) Primary Key
}

When converted to entities, the tables will look like the following:

class Parent{
   int ParentId;
   int valueParent;
   byte[] version;
   virtual ICollection<Child> Children
}

class Child{
   int parentId;
   int childId;
   int valueChild;
   byte[] version;
}

If I load a Parent object, and only update the child entity on it,

parent.Children.ElementAt(0).valueChild = 1 //

In the db, the rowversion in the child entity will increment, but the parent rowversion will remain unchanged. Is that valid? If I want to implement optimistic concurrency I'd still need to do a rowversion check on both parent and child to ensure that the model hasn't changed. I could set concurrency mode to fixed for versions on both entities but that wouldn't prevent having to check at the beginning before I do the update right?

What's the idiomatic way to implement optimistic concurrency if you have 1-many relationships between your entities? Is there some way to do it where I only need to check the parent rowversion or would I need always to check rowversions of any child elements as well?

Optimistic concurrency is checked on every row, and you just need to configure the column as a Timestamp/Rowversion and EF will generate the concurrency checks for you.

Is there some way to do it where I only need to check the parent rowversion

As @Jeremy Lakeman suggests, if you always update the parent when any child changes, then concurreny violations from your EF app can be detected and prevented. But it wouldn't protect against ad-hoc updates to the child rows.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM