我对移动应用程序开发还很陌生,所以我正在努力自学。 我正在为我尝试制作的这个特定应用程序使用 Xamarin 和 sqlite-net(扩展)。
我有 2 个具有 OneToMany 关系的类
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; }
}
现在在我的 Activity 中我有这样的东西
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 进行了一些不同的尝试,但都无济于事。是我做错了什么,还是我没有安装什么? 非常感谢您的帮助。
最佳答案
关于sqlite-net extensions
的事情是你不能“返回”到使用常规 sqlite-net
方法,如果你想获得 child 的关系。因此,您必须在此处遵循他们的文档:
https://bitbucket.org/twincoders/sqlite-net-extensions
它们提供了诸如 GetChildren, UpdateWithChildren, etc
之类的方法您将不得不在其中使用通用 db.Table<T>
方法。
如果您决定使用递归方法,请务必提供可选的 recursive
参数。
因此你应该能够按照以下方式做一些事情:
conn.GetWithChildren<Player>(identifier, recursive: true)
否则请阅读更多关于 Cascade Operations
的内容上面链接的文档部分。
关于c# - 似乎无法使 OneToMany 关系正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40811699/