Table of Contents Previous Section
Should I Make Foreign Key Attributes Class Properties?
You should not make foreign key attributes class properties. If you need to access a foreign key value (because you want to display it in the user interface, for example), you should access it through the corresponding destination object.Class properties that are foreign keys can become out of sync with their corresponding destination objects. For example, assume that an Employee class defines a relationship, department, to its department and has a class property, departmentID, for the corresponding foreign key. Assigning an employee to a new department doesn't update the departmentID property in the employee object until the enterprise object is saved to the database. Thus, departmentID contains the primary key value for the old department while the department relationship points to the new department.
Instead of making the foreign key a class property of an enterprise object, you should implement a method that gets the value from the destination object. For example:
In Java:
public Object departmentID() {In Objective-C:
NSDictionary primaryKey =
EOUtilities.primaryKeyForObject(
department.editingContext(),
department);
return primaryKey.objectForKey("departmentID");
}
- (id)departmentIDIn the Java implementation, the EOUtilities static method primaryKeyForObject returns the primary key dictionary for the department object. In Objective-C, the method is primaryKeyForObject:, which is added to the EOEditingContext description through the EOUtilities category in EOAccess.
{
NSDictionary *primaryKey = [[department editingContext]
primaryKeyForObject:department];
return [primaryKey objectForKey:@"departmentID"];
}
Table of Contents Next Section