dimanche 13 mars 2016

One to Many relationship in SQLite Xamarin

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

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

Aucun commentaire:

Enregistrer un commentaire