OneToMany relationships may not seem to work

I am very new to mobile app development, so I'm trying to teach myself. I am using Xamarin and sqlite-net (extensions) for this particular application that I am trying to make.

I have 2 classes with OneToMany attitude

class Game
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    public string Name { get; set; }

    [OneToMany(CascadeOperations = CascadeOperation.All)]
    public List<Player> Players { get; set; }

    public Game()
    {
        Players = new List<Player>();
    }
}

class Player
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    [MaxLength(8)]
    public string Name { get; set; }

    [ForeignKey(typeof(Game))]
    public int GameId { get; set; }

    [ManyToOne]
    public Game Game { get; set; }

}

Now in my work I have something like this

        SQLiteConnection db = new SQLiteConnection(new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid(), path);

        db.CreateTable<Player>(); 
        db.CreateTable<Game>();

        Game game = new Game();
        game.Name = "Stupid game";

        Game game2 = new Game();
        game2.Name = "Fun game";

        Game game3 = new Game(); 
        game3.Name =  "Amazing game";

        db.Insert(game);
        db.Insert(game2);
        db.Insert(game3);

        Player player = new Player();
        player.Name = name; //Getting this from a input field
        db.Insert(player);

        Random random = new Random();                     
        player.GameId = random.Next(1, 3);
        Game game = db.Get<Game>(player.GameId);
        player.Game = game;

        db.UpdateWithChildren(player);

        game.Players.Add(player);
        db.UpdateWithChildren(game);

All this seems to work and gives me no errors. When I debug this, I see that the player is indeed added to the game. However, when I try to get all the players elsewhere using the following statement,

 List<Player> players = db.Table<Player>().ToList();

they suddenly have no game, and my program crashes when I try to read this property.

UpdateWithChildren InsertWithChildren, . -, , , ? .

+4
1

sqlite-net extensions , "" sqlite-net, . , :

https://bitbucket.org/twincoders/sqlite-net-extensions

, GetChildren, UpdateWithChildren, etc, db.Table<T>.

, recursive.

, - :

conn.GetWithChildren<Player>(identifier, recursive: true)

Cascade Operations , .

0

Source: https://habr.com/ru/post/1661982/


All Articles