Search code examples
c#databasexamarinxamarin.formsrealm

Use lists in a RealmObject on Xamarin


I'm using on a Xamarin Forms project Realm. I have a class A :

public class A: RealmObject
{
    [PrimaryKey]
    public string Id { get; set; }

    public string Name { get; set; }

    public A() : base()
    {
        Id= Guid.NewGuid().ToString();
        Name = $"Unknown_{Id}";
     }
}

And a class B which contains a list of A's objects :

public class B: RealmObject
{
    [PrimaryKey]
    public string Id{ get; set; }
    public string Name { get; set; }

    public IList<A> AList { get; }

    public B() : base()
    {
        Id= Guid.NewGuid().ToString();
        Name = $"Unknown_{Id}";
    }
}

The IList Alist contains object which are already saved on Realm and i would like to save them like references.

The issue is that when i try to add on Realm a B object, i get the exception :

Realms.Exceptions.RealmObjectManagedByAnotherRealmException: Cannot start to manage an object with a realm when it's already managed by another realm

This exception appears on the line realm.Add(newB, update: true); in the code bellow

private void AddB(B b)
    {
        var realm = GetRealmInstance();

        using (var trans = realm.BeginWrite())
        {
            var newB = new B();
            newB.Name = b.Name;
            newB.Id = b.Id;

            foreach (var element in b.AList)
            {
                newB.Devices.Add(element);
            }

            realm.Add(newB, update: true);
            trans.Commit();
        });

        OnChanged?.Invoke();
    }

I have to precise that all objects in the AList are already saved on Realm.

Thanks in advance.


Solution

  • How about:

            var newB = new B();
            newB.Name = b.Name;
            newB.Id = b.Id;
    
            realm.Add(newB, update: true);
    
            foreach (var element in b.AList)
            {
                newB.Devices.Add(element);
            }
    
            trans.Commit();