objectbox / objectbox-dart

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

<Bad state: ToOne relation field not initialized. Make sure attach(store) is called before using this.> #677

Closed MRtootisabz closed 1 month ago

MRtootisabz commented 1 month ago

Is there an existing issue?

Build info

Steps to reproduce

  1. made object box singletone db in flutter
  2. load object box from local then load data from rest api and update local data
  3. get data convert from json to model and put data to object box.

Expected behavior

i want to update box with new data. when get data from server i update the model my model has a toOne relation. I update the to one relation model target and targetId. it give this error : <Bad state: ToOne relation field not initialized. Make sure attach(store) is called before using this.>

issue: data not updating in object box

@override
  Future<void> updateRoom(RoomEntity room) async {
    final mRoom = await objectBox.roomBox.getAsync(room.id);
    int i = await objectBox.roomBox.putAsync(room);
    print(i);
  }

entity class:

@Entity()
class RoomEntity {
  final lastMessage = ToOne<RoomMessageEntity>();
 RoomEntity({});

factory RoomEntity.fromJson(Map<String, dynamic> json) {
    final room = RoomEntity();

    if (json['last_message'] != null) {
      final lstMessage = RoomMessageEntity.fromJson(json['last_message']);
      room.lastMessage.targetId = lstMessage.id;
      room.lastMessage.target = lstMessage;
    }

return room;
}}
greenrobot-team commented 1 month ago

Thanks for reporting! However, the code you have given can not throw this exception. Maybe you can share what code line throws the error?

Maybe some helpful pointers:

Optimization: for convenience, an object with a ToOne will put the target object as well if the ID of the target object is 0.

Note: I labeled this issue with "more info required" so it will auto-close in a few days if there are no follow-up comments.

MRtootisabz commented 1 month ago

thank you for your response, this solved my problem.