下面是我看过的文档,可能会有帮助:Sample SQLite OneToMany Unit Test和General Read and Write Documentation in Readme
我的用例是,我已经插入了一个Item
,现在我正在编辑一个Item
,所以我需要更新Item
记录并插入n个ItemPhoto
记录,基本上,我说的是SaveItem(..)
的情况。
当我逐步执行代码以写入数据库时,我似乎看到所有键都被适当地分配给了内存中的对象。稍后,当我通过调用GetWithChildren(..)
来读取Item
时,除了一种情况外,ItemPhotos
属性的计数为0。只有在ItemPhotoId
为0的情况下,ItemPhotos
才会真正得到填充。我最好的猜测是,在运行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;
}
}
...
}
1条答案
按热度按时间wvmv3b1j1#
我通过删除现有的表并重新创建它们来修复它,之前只是将
ItemPhoto
的ItemPhotoId
属性重命名为Id
。也许库假设主键名为Id
,或者我在此过程沿着更改了模型方面的其他内容,这些模型只需要重新创建表而不是迁移?此外,更简单的尝试保存只与Database.InsertOrReplaceWithChildren(item);
似乎工作得很好,所以我去与它的价值。