Two-Way Relationship

Good Day,

Is it possible (with the .NET-SDK) to produce a Database, which would look like the following example?

Suppose I Have a Class Dog and Owner

public class Owner : RealmObject
{
    [PrimaryKey, MapTo("id")]
    public int ID { get; init; }
    
    [MapTo("name"), Required]
    public string Name { get; set; }

    [MapTo("dogs"), Backlink(nameof(Dog.Owner))]
    public IQueryable<Dog> Dogs { get; }
}

public class Dog : RealmObject
{
    [PrimaryKey, MapTo("id")]
    public int ID { get; init; }
    
    [MapTo("name"), Required]
    public string Name { get; set; }
    
    [MapTo("owner")]
    public Owner Owner { get; set; }
}

This produces a Database, where each Owner has two columns and each Dog has three columns.
Each dog contains a reference to its owner.

Is it possible to additionally reference from a Owner to its dogs, without losing the reference back to the Owner?

I found some code using the Swift-SDK, which used LinkingObjects. This code seemed to achieve what I want, but LinkingObjects are not available in .NET.

Hi Tim!

Welcome to the MongoDB forum!

Your example is 100% correct from what I can see here. :slight_smile:
The Backlink is exactly what you need.
I assume you found it already looking at the your code but in case you have not, here is our documentation for inverse relationships: https://www.mongodb.com/docs/realm/sdk/dotnet/fundamentals/relationships/#std-label-dotnet-inverse-relationship

The thing that might be confusing is that the Backlink is not part of the Realm when you open it with RealmStudio. We don’t persist backlinks since the information about them is already persisted by the forward link (which in you case is the Owner in Dog).

So, while not all properties are persisted, your code example should do exactly what you are looking for.

Let me know if you have any other question or want me to clarify this further in any way.

All the best,
Dominic

1 Like

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