c# - SQLite Xamarin 中的一对多关系

标签 c# sqlite xamarin sqlite-net sqlite-net-extensions

我正在构建一个 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/

相关文章:

c - sqlite3库 undefined reference 错误

android - 类型干扰失败。 Kotlin 和 Anko 中的预期类型不匹配 : required String found pair<String, String>

android - 带有 ImageView 和 TextView 的 AlertDialog

c# - 当我的代码不存在时,我如何让我的代码创建一个 sqlite 数据库?

c# - Xamarin-在Gridview中创建一个额外的列,其垂直跨度为2

c# - ServiceReferences.ClientConfig 中的动态端点

c# - 只读(视觉上)复选框

c# - 如何配置 asp.net webforms WebMethod 日期格式

SQLite 和递归触发器

c# - 如何将 vector<double> 从 C++ 编码到 C#