I have two classes and one of them has a relation to another:
public FirstClass
{
public string Name {get; set;}
public string Age {get; set;}
}
and another class where I use this realm object like this for the to-many relationship:
public OtherClass
{
public IList<FirstClass> From {get; set;}
public IList<FirstClass> To {get; set;}
}
my Problem is that for each saving of a new OtherClass the FirstClass is also saved as a new one. But I want that if the same FirstClass is saved that it has a link to the saved one and no duplicate is created. Is that possible? And if yes how?
FirstClass
doesn't have a primary key defined, so there's no way for Realm to know that you want an existing instance. You can add a primary key on FirstClass
and then do something like:
public FirstClass : RealmObject
{
[PrimaryKey]
public int Id { get; set; }
// Other properties
}
var otherClass = ...;
realm.Write(() =>
{
realm.Add(otherClass, update: true);
});