Using Integer (Identity) Primary Keys

The basic concept used by business objects that use auto-increment (identity) integer fields as primary keys is identical to guid-based business objects. However, in addition to specifying the master entity and primary key field names, we also have to switch the business object into IndentityKey mode. The following example shows a simple C# exmaple for a business object that can modify the Employees table in the SQL Northwind database example:

public class EmployeeBO : BusinessObject { protected override void Configure() { this.MasterEntity = "Employees" ; this.PrimaryKeyField = "EmployeeID" ; this.PrimaryKeyType = EPS.Data.KeyType.IntegerAutoIncrement; } }

The important part is the very last line of this sample, which indicates to the business object that an auto-increment primary key is to be used.

Note that there are some far-reaching implication when using identity keys. Whenever an identity key is used, data that is created on the client machine needs to be assigned a temporary key until that data is saved to the database, which will trigger the actual creation of the real identity key. Milos automatically creates temporary keys on the client. All these temporary keys are negative (minus) values (and are therefore easy to spot). Once the data gets saved to the database, SQL Server (or whatever the database may be) will automatically create real identity keys. At that point, the data on the client is out of sync with the data on the server. While "real" keys are used on the server, the client still has the temporary keys. Milos will therefore query the database to retrieve the keys that were actually generated and replace the temporary key in the updated row, so the row can later be re-identified. There are a few important aspects to this however:


  1. This requires that Milos has access to the database in some form, so the actual keys can be queried. This means that integer keys can not be used in offline scenarios.
  2. Important: Tables that are related to the table that was just saved were linked through the temporary keys. For instance, if we create a new employee, that employee will receive the key "-1" until it is saved the first time. Once the employee is saved, that id will be replaced with a real indentity key, such as "25". Milos handles all of that automatically. However, there might be related tables, such as EmployeeTerritories. Lets say we also created two new territories, which will receive the keys -1 and -2 respectively. Both of those records would be linked to employee -1. Once employee -1 is assigned the key 25 however, the two territory records become orphaned untill their foreign key is updated to 25 as well. This needs to be handled in the PrimaryKeyValueChanged() method of the business object.
    1. (See also: HowTo_CreateChildItemsInEntities).


Last Updated: 8/7/2006