objectbox / objectbox-dart

Flutter database for super-fast Dart object persistence
https://docs.objectbox.io/getting-started
Apache License 2.0
918 stars 116 forks source link

Bad state: ToOne relation field not initialized thrown when accessing target #613

Closed giordy16 closed 1 month ago

giordy16 commented 1 month ago

Build info

Problem

In my app I have a 3 layer architecture to represent objects: json, obox and domain. I want to update the Articles of my app through an API call. To parse the users that I receive from the server, I do: ArticleJson.fromJson(item).convertToObox().convertToDomain(), where two converters are two extension function to create the object of the upper layer.

ArticleObox convertToObox() {
  ArticleObox obox = ArticleObox(
      id: id,
      articleNumber: articleNumber,
      country: country,
      name: name,
      plu: plu,
      reserveBoolean00: reserveBoolean00,
      reserveBoolean01: reserveBoolean01,
      reserveBoolean02: reserveBoolean02,
      reserveDate00: convertDateTimeFromJson(reserveDate00),
      reserveDate01: convertDateTimeFromJson(reserveDate01),
      reserveVarchar00: reserveVarchar00,
      reserveVarchar01: reserveVarchar01,
      reserveVarchar02: reserveVarchar02);

      obox.articleGroup.targetId = articleGroupId;
      obox.state.targetId = stateId;
  return obox;
}

Article convertToDomain() {
  Article domain = Article(
      id: id,
      articleNumber: articleNumber,
      country: country,
      name: name,
      plu: plu,
      reserveBoolean00: reserveBoolean00,
      reserveBoolean01: reserveBoolean01,
      reserveBoolean02: reserveBoolean02,
      reserveDate00: reserveDate00,
      reserveDate01: reserveDate01,
      reserveVarchar00: reserveVarchar00,
      reserveVarchar01: reserveVarchar01,
      reserveVarchar02: reserveVarchar02);

  domain.articleGroup = articleGroup.target?.convertToDomain();

  domain.state = state.target?.convertToDomain();

  return domain;
}

My problem is that when I call convertToDomain(), Bad state: ToOne relation field not initialized. Make sure attach(store) is called before using this. is thrown when I try to access articleGroup.target, and I don't really understand where should I call attach(store).

I overall need to to pass through the Obox level because on the JSON level I just have the foreign key of some properties, instead on the domain level I want to have the object it self, and on the Obox level I build this link.