Hi,
I have a question regarding updating an entry in a write operation with data already existing in the database but provided from outside. Consider this:
public class Game : RealmObject
{
[PrimaryKey] long Id { get; set; }
public ISet<User> Players { get; }
/* Other Properties */
}
public class User: RealmObject
{
[PrimaryKey] long Id { get; set; }
public string Name { get; set; }
[Backlink(nameof(Game.Players))]
public IQueriable<Game> Games { get; }
}
Now, I want to update the Game Object with new Data, including new Users:
realm.write( () =>
{
/* This code does not work */
// myPlayer comes from a different method and is not retrieved from the database
if ( !myGame.Players.Contains( myPlayer ) )
myGame.Players.Add(myPlayer); // <-- this is the problem code
/* This code works */
if ( !myGame.Players.Contains( myPlayer ) )
{
var player = realm.Find<User>( myPlayer.Id ) ?? myPlayer;
myGame.Players.Add( player );
}
/* This code should work as well */
var game = myGame.GetDeepCopy();
game.Players.Add( myPlayer );
realm.Add( game, update:true );
});
The problem arises when the user is not yet a player for the game and gets added, but already exists in the database. I get the player from a different source, not from the database. I know the name and id correctly, that is not a problem. All I want is to add it to the game. But that will through an exception for an already existing primary key.
If I search for the player by Id and add the realm object instead it works. But since I know that the player is not modified in any way and it only gets added to the Player list of the game, retrieving this object is just needless overhead.
In my actual code, this would have to be done for multiple types with multiple objects each, so for one “Game” it would have to be done a dozen times, and for hundreds or even thousands of “Games”. So it would be quite a lot of overhead.
Right now I see only two ways of adding the player to the game in my example, either retrieve the objects and add those to the list or create a copy, add the non-realm object to the copy and upsert them to the realm database (I assume, didn’t test this version).
Does someone have a way to do this without any needless searches or copies?