I'm very new to Mobile App Development so i'm trying to teach myself. I'm using Xamarin and sqlite-net (extensions) for this particular app i'm trying to make.
I have 2 classes with a OneToMany relationship
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 activity 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);
This all seems to work and gives me no errors. When I debug this I can see that the player is indeed added with a Game. However when I try somewhere else to get all the players using the following statement,
List<Player> players = db.Table<Player>().ToList();
they suddenly don't have a Game anymore and my program crashes when I try to read that property.
I've tried a few different things with the UpdateWithChildren and InsertWithChildren but to no avail. Is there something I'm doing wrong or is it something I haven't installed or? I really appreciate the help.