One to Many relationship in SQLite Xamarin

Libin Joseph picture Libin Joseph · Mar 13, 2016 · Viewed 8k times · Source

I am building a Xamarin mobile app, and I have a set of products that I get from a rest api. Each product can have n number of images. I have set the relationship of the table using SQLite-Net Extensions. However, when I insert the values into the database, Images field has null value in the Product table and the Image table in empty.

My Model

    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; }
}

The code that I am using to insert values.

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);

This is how i deserialise json to object

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;
    }

It will be great if someone can help me in identifying what am I doing wrong.

Answer

Artem Zelinskiy picture Artem Zelinskiy · Mar 14, 2016
db.InsertAllWithChildren(data);
db.UpdateAll(data); 

You insert values with their child values, and then update with same values, with ProductID values being updated with null, as they should be set by database. If you want to update your data, your should set foreign key for each item being inserted, or use UpdateWithChildren