【问题标题】:One to Many relationship in SQLite XamarinSQLite Xamarin 中的一对多关系
【发布时间】:2016-03-13 20:12:46
【问题描述】:

我正在构建一个 Xamarin 移动应用程序,并且我有一组从 rest api 获得的产品。每个产品可以有 n 个图像。我已经使用 SQLite-Net Extensions 设置了表的关系。但是,当我将值插入数据库时​​,Images 字段在 Product 表中为空值,而 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;
    }

如果有人能帮助我找出我做错了什么,那就太好了。

【问题讨论】:

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


    【解决方案1】:
    db.InsertAllWithChildren(data);
    db.UpdateAll(data); 
    

    您插入带有子值的值,然后使用相同的值进行更新,其中 ProductID 值被更新为 null,因为它们应该由数据库设置。如果你想更新你的数据,你应该为每个被插入的项目设置外键,或者使用 UpdateWithChildren

    【讨论】:

      【解决方案2】:

      我猜dataList&lt;Product&gt;。在这种情况下,您只是在数据库中插入产品,没有插入图像。

      您有两种选择:手动插入图像或使用递归操作。


      要手动插入图片,只需在插入产品之前调用InsertAll 方法和您的所有图片:

      List<Image> images = data.SelectMany(p => p.Images ?? new List<Image>());
      conn.InsertAll(images);
      conn.InsertAllWithChildren(data);
      

      使用递归操作更简单,但需要少量配置。通过设置关系属性的CascadeOperation 属性来启用级联操作:

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

      然后,您可以将任意-WithChildren方法的recursive参数设置为true进行级联操作:

      conn.InsertAllWithChildren(data, recursive: true);
      

      【讨论】:

      • 这两种方法我都试过了。对于第一种方法。当我通过代码进行调试时,我在行后失去了调试控制。 List images = data.SelectMany(p => p.Images).ToList();,并且在该行执行后焦点不会返回。而且我检查了数据,也没有被填充。对于第二种方法,代码执行良好,但没有列出图像。
      • 可能有些Images 为空?我添加了空合并运算符来解决它。 “没有列出图像”是什么意思?您是使用数据库浏览器还是以编程方式列出元素?如果是第二个,您应该显示您的代码。
      猜你喜欢
      • 1970-01-01
      • 2015-11-11
      • 2018-10-08
      • 1970-01-01
      • 2016-10-04
      • 1970-01-01
      • 2014-01-29
      • 2015-02-14
      • 2021-01-07
      相关资源
      最近更新 更多