【发布时间】:2023-01-19 03:41:45
【问题描述】:
这是我看过的文档,可能会有帮助:Sample SQLite OneToMany Unit Test和General 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