Unable to save modifications of a Lazy<TMemoryStream> field

Issue #311 on hold
Leonid Huber created an issue

I load data into an Entity object with a Lazy<TMemoryStream> field. After that I change data in this field and try to save it. No changes appear in the database BLOB field. I use PostgreSQL database server. These are steps to reproduce:

Create database table and fill it with data:

CREATE TABLE public.t_bytea ( id int4 NOT NULL, bdata bytea NULL, CONSTRAINT t_bytea_pk PRIMARY KEY (id) );

INSERT INTO public.t_bytea (id, bdata) VALUES(1, decode('48656C6C6F2C20776F726C6421','hex'));

Create entity class:

[Entity] [Table('t_bytea')] TByteA = class private [Column('id', [cpRequired, cpPrimaryKey, cpNotNull], 0, 0, 0, 'Primary Key')] FId: Integer; [Column('bdata', [], 50, 0, 0, 'BLOB')] FByteA: Lazy<TMemoryStream>; function GetByteA: TMemoryStream; procedure SetByteA(Value: TMemoryStream); public constructor Create; property ID: Integer read FId; property ByteA: TMemoryStream read GetByteA write SetByteA; end;

constructor TByteA.Create; begin FByteA := Lazy<TMemoryStream>.Create( function : TMemoryStream begin Result := TMemoryStream.Create; end, True ); end;

function TByteA.GetByteA: TMemoryStream; begin Result := FByteA; end;

procedure TByteA.SetByteA(Value: TMemoryStream); begin if Assigned(Value) then FByteA.Value.LoadFromStream(Value) else FByteA.Value.Clear; end;

Load data into the entity, modify it and try to save data back to the table:

procedure TForm1.btnAddClick(Sender: TObject); var LStream: TMemoryStream; LStreamWriter: TStreamWriter; LEntity: TByteA; LEntityWrapper: TEntityWrapper; begin LStream := TMemoryStream.Create; LStreamWriter := TStreamWriter.Create(LStream); LEntity := FSession.SingleOrDefault<TByteA>('SELECT * FROM t_bytea WHERE id = 1', []); try LStreamWriter.WriteLine('Hello, world!' + DateTimeToStr(Now)); LEntity.ByteA.LoadFromStream(LStream); // Save modified entity FSession.Save(LEntity); finally LStreamWriter.Close; LStreamWriter.Free; LEntity.Free; end; end;

And there is another one issue. When I load data into an entity object and a BLOB field in a database table is NULL then it's impossible to modify this field in the entity object at all. This is because FByteA.Value does not contain a TMemoryStream object and there is no way to create it properly. If I'm wrong please explain how to do it properly.

Best regards, Leonid.

Comments (4)

  1. Log in to comment