微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 似乎无法使OneToMany关系正常工作

我是移动应用程序开发的新手,所以我正在努力自学.
我正在尝试使用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; }

}

现在,在我的活动中,我有类似的东西

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扩展的事情是,如果你想获得子关系,你不能“回”使用常规的sqlite-net方法.因此,您必须遵循他们的文档:

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

它们提供了诸如GetChildren,UpdateWithChildren等方法,您必须在其中使用泛型db.Table< T>.方法.

如果您决定使用递归方法,请确保提供可选的递归参数.

因此,你应该能够做到以下几点:

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

否则,请阅读上面链接的文档的Cascade Operations部分.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐