我對移動應用程序開發非常陌生,所以我試圖教自己。 我正在使用Xamarin和sqlite-net(擴展)爲這個特定的應用程序,我試圖使。似乎無法獲得OneToMany關係工作
我有2個班級,一對多的關係
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; }
}
現在在我的活動我有這樣的事情
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);
這一切似乎工作,並沒有給我的錯誤。當我調試這個時,我可以看到玩家確實添加了一個遊戲。然而,當我嘗試別的地方使用下面的語句獲取所有的球員,
List<Player> players = db.Table<Player>().ToList();
他們突然沒有了遊戲,我的程序崩潰時,我嘗試讀取該屬性。
我已經嘗試了一些與UpdateWithChildren和InsertWithChildren不同的東西,但無濟於事。有什麼我做錯了,還是我沒有安裝或? 我真的很感謝幫助。
你有沒有試過'WithChildren'的讀法? – redent84
我相信''UpdateWithChildren'中可能需要遞歸的第二個參數。如果不存在,你必須通過''read''方法通過'conn.GetWithChildren(identifier,recursive:true);' –
Ah GetWithChildren確實是正確的。謝謝!! – Jinse