Bob Horn
Bob Horn

Reputation: 34297

Linq-to-Sql Timestamp Spanning Two Tables

I'm using a SQL Server timestamp column (called VersionNumber) to support optimistic concurrency with Linq-to-SQL. This works well when only one table is involved. However, I have domain entities that look like this:

Person: FirstName, LastName, Age, VersionNumber
Doctor: all Person properties + Profession
Athlete: all Person properties + Sport, YearsPro
Musician: all Person properties + Instrument

My DB has a Person table and then other tables for each type of Person. The concrete tables (like Athlete) only have the columns necessary for athlete. The concrete tables have a 1-1 mapping with the Person table. How do I use VersionNumber in this case? Can/should the concrete tables have their own VersionNumber column? Should just the Person table have the VersionNumber column? How should I save data in this scenario?

In this particular case, I want to save Athlete. Right now, only the Person base class has VersionNumber. I'm just not sure how to save this.

Note: Because Person already has a VersionNumber property in the C# domain entity, I can't add that same property name to the concrete classes.

Upvotes: 0

Views: 174

Answers (1)

Anders Abel
Anders Abel

Reputation: 69250

linq-to-sql supports single table inheritance, so if you are free to redesign your database, you should create one table, with all the fields. Then you add a type field which will tell linq-to-sql which concrete type materialize for each particular row.

If that's not an option, the optimistic locking have to be done on a per table basis. Add a VersionNumber column to each table and linq-to-sql will use it. The way you have it right now also works. Linq-to-sql will use the VersionNumber of the Person table and fall back to asserting that each property is unchanged when updating the other tables. If any of the properties have been changed in the DB since they were red, linq-to-sql will fail the update with a concurrency error.

Upvotes: 1

Related Questions