Add to collection of unmanaged objects


How to add a child object to a the collection of a parent of unmanaged objects?

public class Order : RealmObject
    public string OrderId { get; set; }

    public IQueryable<OrderDetail> OrderDetails { get; }
public class OrderDetail : RealmObject
    public string OrderDetailId { get; set; }
    public Order Order { get; set; }
realm.Write(() =>
    Order order = new Order()
    order.OrderId = ....;
    realm.Add(order, update true);

    OrderDetail detail = new OrderDetail();
    detail.OrderDetailId = ....;
    detail.Order = order; 

This adds the detail to order.OrderDetails. However where the objects are unmanaged
detail.Order = order
does not add the detail to order.OrderDetails. It appears that to add a child to a collection of a parent where the objects are unmanaged, the parent must implement
public IList<OrderDetail> OrderDetails { get; }

Am I correct, or is it possible to add to a collection of unmanaged objects that are referenced as backlinks?


Yes, that is correct. Backlink properties are computed based on the information in the Realm.


Thanks @nirinchev. I add this in case others face similar issues:

We use the MVVM pattern and can’t use live objects in the presentation layer so need a mechanism to add child objects to collections outside the realm.

I kept our original poco model classes with lists of child objects and implemented equivalent types as RealmObject which used backlinks, then build a mapping layer to map between the two object types. This worked well but was a lot of code.

I’m now working through developing a different architecture which uses one set of model classes but parent types implement both backlings and IList for child collections. There is still mapping between managed an unmanaged objects, but so far seems simpler.