In my app, an article can have many elements, and each article element has a unique ordinal position from 0 up to 1 less than the total number of elements in the article. For example, an article can have a deck at position 0, a different kind of article element at position 1, and so on, and the elements can be reordered with drag and drop.
The article element classes derive from a base class and are stored in one database table with a discriminator column (I would call this single table inheritance but in EF Core it is called table-per-hierarchy mapping). There is a database constraint on this table that enforces uniqueness of the ordinal position for the elements of the same article. To change the ordinal position of an element without violating the constraint, some of the other elements need to be shifted up or down. Similarly, the sibling elements need to be shifted when adding a new element or deleting one.
The app uses a Clean Architecture approach where data access is encapsulated in an Infrastructure project that uses the Repository design pattern. Reordering things may not seem like a concern of the infrastructure layer, but in this case, it is necessary to do during data access with those ordered records.
My current approach is of an abstract repository interface with an API for create, update, and delete of an ordinal child entity:
This is in the application core project of the clean architecture; the infrastructure project will provide the implementation.
This is the IOrdinalChild interface:
This is the base class for article element entity classes:
Here is the base class that implements the interface:
And a class derived from that:
IDeckRepository adds some interface that is not related to the ordered elements too:
When updating an ordered element, it’s necessary to retrieve the ordinal position of the record to be updated from the database. This can potentially lead to the Change Tracker tracking two instances of the same entity and SaveChanges will throw an error. That is avoided here with a non-tracking query.