【问题标题】:How To Read and Write Records In SQLite Using SQLite Net Extensions?如何使用SQLite Net Extensions在SQLite中读写记录?
【发布时间】:2023-01-19 03:41:45
【问题描述】:

这是我看过的文档,可能会有帮助:Sample SQLite OneToMany Unit TestGeneral Read and Write Documentation in Readme

我的用例是我已经插入了一个Item,现在我正在编辑一个Item。所以我基本上需要更新 Item 记录并插入 n ItemPhoto 记录。基本上,我说的是 SaveItem(..)Item.Id != 0 的情况。

似乎当我逐步执行代码以写入数据库时​​,我看到所有键都被适当地分配给内存中的对象。但是,稍后当我通过调用 GetWithChildren(..) 来读取 Item 时,除了一个 ItemPhotos 属性的计数为 0 之外的所有情况。唯一一次实际填充 ItemPhotos 的情况是 @987654333 @ 为 0。我最好的猜测是,在运行 GetWithChildren(..) 之前未设置 ItemPhotoId,然后它仅在内存中的默认值 0 实际上与给定项目的数据库的 ItemPhotoId 匹配时才有效。

这是我的代码,显示模型和读写代码:

public class Item
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }

    public string Text { get; set; }

    public string Description { get; set; }

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

public class ItemPhoto
{
    [PrimaryKey, AutoIncrement]
    public int ItemPhotoId { get; set; }

    [ForeignKey(typeof(Item))]
    public int ItemId { get; set; }

    public string FileLocation { get; set; }

    [ManyToOne]      // Many to one relationship with Item
    public Item Item { get; set; }
}

class SqlLiteDataStore
{
    static SQLiteConnection Database;

    ...

    public Item GetItem(int id)
    {
        return Database.GetWithChildren<Item>(id, true);
    }

    public Item SaveItem(Item item)
    {
        // Simpler Attempt #1
        // Database.InsertOrReplaceWithChildren(item);
        // return item;

        // Manual Attempt #2
        if (item.Id != 0)
        {
            foreach (var photo in item.ItemPhotos)
            {
                if (photo.ItemPhotoId == 0)
                    Database.Insert(photo);
            }
            Database.UpdateWithChildren(item);

            return item;
        }
        else
        {
            Database.InsertWithChildren(item, true);
            return item;
        }
    }

    ...

}

【问题讨论】:

    标签: sqlite xamarin xamarin.forms sqlite-net sqlite-net-extensions


    【解决方案1】:

    好吧,我通过删除现有表并重新创建它们来修复它,并且事先只是将 ItemPhotoItemPhotoId 属性重命名为 Id。也许库假定主键名称为 Id,或者我可能在模型方面更改了其他一些东西,只需要重新创建表而不是迁移表?此外,仅使用 Database.InsertOrReplaceWithChildren(item); 进行保存的更简单尝试似乎工作得很好,所以我将按照它的价值进行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-19
      • 2011-05-17
      相关资源
      最近更新 更多