Setting Parent ID (foreign key value) directly

Hi,

Suppose I have to entities (TParent and TChild) in a 1:M relationship. Both entities have a single field ID (primary key) and TChild has a single field ParentID (foreign key). In my case, all key fields are GUID's.

I am writing an import routine where I read all entities from an XML file that contains all ID's and ParentID's. Obviously I can set the ID fields directly to their GUID value, but is there a manner in which I can set the ParentID field value (GUID) of a newly created TChild entity directly?

Of course, I can use the GUID to obtain the relevant TParent entity and then set the TChild.Parent property to that entity, but that would involve multiple queries when importing the (sometimes) large file. I have looked at the definition of Proxy but KeyValue appears to be read-only.

Regards,
Mark

That should be as simple as doing

Parent.Id := ParentId;
Child.Id := ChildId;
Child.Parent := Parent;

Clearly. However, Parent (Child.Parent := Parent) is an Entity. The question was whether there is a way in which I can simply set the GUID value (i.e. the value of the underlying Foreign Key field):

Child...???... := ParentID_GUID

The idea is that for each "record" in the file, I wish to create a new entity, set the GUID value (and all other properties) and Save/Merge/Replicate it to the database. This way I do not have to get the associated entity and thereby reduce the number of SQL's to execute.

Having said that; on further thought I realized that the parent record was in the same import file so if I am not mistaken, I can simply execute:

Child.Parent := ObjMgr.Find<TParent>(ParentID)

There will be no additional SQL involved as the TParent is already in the Object Manager….

Nevertheless, I am still curious if there's a possibility to set the GUID value (for Child.Parent) directly. I think that in some situations it may be useful.

Thanks and regards,
Mark

Correct, the parent is already in the manager and that's the best way to do, as it won't execute any SQL but retrieve from cache.

You can also create the Parent object in advance and add it to the manager before making the Find calls:

Parent := TParent.Create;
Parent.Id := ParentID;
ObjMgr.Update(Parent);

But note that you have to be sure that the Parent object will never be flushed, otherwise the record in the database will be updated and the missing properties will be set to null.