我正在构建一个 Xamarin 移动应用程序,并且我有一组从 Rest api 获得的产品。每个产品可以有n张图像。我已经使用 SQLite-Net 扩展设置了表的关系。但是,当我将值插入数据库时,Product 表中的 Images 字段为空值,而 Image 表为空。
我的模型
public class Product
{
[SQLite.Net.Attributes.PrimaryKeyAttribute]
public int ID { get; set; }
public string Name { get; set; }
[OneToMany]
public List<Image> Images { get; set; }
}
public class Image
{
[SQLite.Net.Attributes.PrimaryKeyAttribute, SQLite.Net.Attributes.AutoIncrement]
public int ID { get; set; }
[ForeignKey(typeof(Product))] // Specify the foreign key
public int ProductID { get; set; }
public string Link { get; set; }
}
我用来插入值的代码。
var db = new SQLiteConnection(new SQLitePlatformAndroid(), path);
var info = db.GetTableInfo("ProductDB");
db.CreateTable<ProductDB>();
db.CreateTable<ImageDB>();
db.DeleteAll<ProductDB>();
db.DeleteAll<ImageDB>();
db.InsertAllWithChildren(data);
db.UpdateAll(data);
这就是我将 json 反序列化为对象的方式
public async Task<List<ProductDB>> GetAllProducts()
{
var httpClient = GetHttpClient();
var response = await httpClient.GetAsync(ServiceEndPoints.GetFilmsUri).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var content = response.Content;
string jsonString = await content.ReadAsStringAsync().ConfigureAwait(false);
return JsonConvert.DeserializeObject<List<ProductDB>>(jsonString);
}
return null;
}
如果有人能帮助我找出我做错了什么,那就太好了。
最佳答案
db.InsertAllWithChildren(data);
db.UpdateAll(data);
您插入值及其子值,然后使用相同的值进行更新,其中 ProductID 值更新为 null,因为它们应该由数据库设置。如果你想更新你的数据,你应该为每个插入的项目设置外键,或者使用UpdateWithChildren
关于c# - SQLite Xamarin 中的一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35975235/