Short cut to get only first entity

Hi,
Is there faster way to code finding only one entity using .Where() ?
For example product entity has barcode field which is unique but not primary key (can contain empty values but exists values are unique).
Now i think the best solution is with class helper

function TomHelper.FindOne<t>(aCrit: TCustomCriterion ): t;
var
  lList: tlist<t>;
begin
  lList := Find<t>.where(aCrit).list ;
  try
    if lList.Count> 0 then
      result := lList[0]
    else
      result := nil;
  finally
    llist.Free;
  end;
end;

And then call

lproduct  := lObjMgr.findOne<tProduct>(Linq['barcode'] = aBarcode);

Haven't actually checked how much overhead comes from creating a list, but my internal ms-dos programer inside my heads screams... :rofl:

Sure, use UniqueResult:

  TheOne := Find<t>.where(aCrit).UniqueResult;

It even has the advantage of raising an exception if more than one record is found, so you are sure that your aCrit must return a single value.

2 Likes

This happens when you rely on code completion and look documentation after you have found suitable looking method/propery :). I remember seen uniqu result but I immediately thought that is has something to do with union or select distinct ... :smiley:
thanks !!

1 Like

This topic was automatically closed 60 minutes after the last reply. New replies are no longer allowed.