#1 2015-03-30 09:47:19

volax
Member
Registered: 2015-01-20
Posts: 3

How to create new entity with linked entity?

Hi!

I'm stuck in creating new entity with link to already existing entity of other type.

My simplified model:

  TSystemUser = class(TSQLRecord)
  private
    fUserName: string;
  published
    property UserName: string read fUserName write fUserName;
  end;

  TSystemSession = class(TSQLRecord)
  private
    fSystemUser: TSystemUser;
    fStartTime: TDateTime;
  published
    property SystemUser: TSystemUser read fSystemUser write fSystemUser;
    property StartTime: TDateTime read fStartTime write fStartTime;
  end;

I'm loading user from DB (PostgreSQL with ZEOS) and creating user session like this:

var
  vUser: TSystemUser;
  vSession: TSystemSession;
begin
  vUser := TSystemUser.CreateAndFillPrepare(fRestServer, 'username=?', ['volax']);
  try
    if vUser.FillOne then
    begin
      vSession := TSystemSession.Create;
      try
        vSession.StartTime := Now;
        vSession.SystemUser := vUser;
        // Adding user's session:
        fRestServer.Add(vSession, True);
      finally
        vSession.Free;
      end;
    end;
  finally
    vUser.Free;
  end;

After call to fRestServer.Add(vSession, True); the session created, but value of SystemUser field in SystemSession table looks to be pseudo-random value, StartTime seems to be correct.

Can anyone explain, what's wrong with my code?

Thank you!

Last edited by volax (2015-03-30 09:47:34)

Offline

#2 2015-03-30 11:01:28

lele9
Member
Registered: 2011-10-28
Posts: 170

Re: How to create new entity with linked entity?

Hi,
the ORM save the TSQLRecord's ID in database and not the Entity.
it's clear in Documentation.
So you must write
vSession.SystemUser := vUser.ID;

hope it's useful...

Offline

#3 2015-03-30 11:05:01

ab
Administrator
From: France
Registered: 2010-06-21
Posts: 14,655
Website

Re: How to create new entity with linked entity?

By default, TSQLRecord published properties are IDs, not instances.
See http://synopse.info/files/html/Synopse% … ml#TITL_70

So you should store the ID in the published property, not an instance:

 vSession.SystemUser := vUser.AsTSQLRecord;

Offline

#4 2015-03-30 11:23:25

volax
Member
Registered: 2015-01-20
Posts: 3

Re: How to create new entity with linked entity?

lele9,

lele9 wrote:

vSession.SystemUser := vUser.ID;

I've publish property of a type TSystemUser, not TId, so I need to assign instance of TSystemUser to it.

ab,

ab wrote:
vSession.SystemUser := vUser.AsTSQLRecord;

See http://synopse.info/files/html/Synopse% … ml#TITL_70

So you should store the ID in the published property, not an instance:

vSession.SystemUser := vUser.AsTSQLRecord;

Thank you very much! Works like a charm!

Alexander.

Offline

Board footer

Powered by FluxBB