mercredi 21 octobre 2015

How can a foreign key be mapped onto an object field in SQLite-Net Extensions?

Context: We are using SQLite-Net Extensions for local data caching with Xamarin. We plan on deploying to iOS, Android and Windows Phone. We have existing data structures used throughout our system (all implementing a common interface) that we would like to store in this manner.

Problem As shown in the code sample, the [ManyToOne] attribute is used to signify a relation field. This does not work. As described on the BitBucket Developer Page the [ForeignKey] attribute can be used to specify the foreign key relation. This seemingly only supports an int. Can we easily adapt our structure to support these relations without duplicating the properties for the Id field. e.g. the following is undesirable.

    [ForeignKey(typeof(Address))]
    public int AddressId { set; get; }

    [ManyToOne]
    public Address Address
    {
        set { address = value; }
        get { return address; }
    }

Code Sample

using SQLite.Net.Attributes;
using SQLiteNetExtensions.Attributes;

namespace Data
{
    [Table("Client")]
    public class Client : IData
    {
        private int id = -1;
        private Address address = null;

        public Client() { }

        public Client(int id)
        {
            this.id = id;
        }

        [PrimaryKey, AutoIncrement, Column("_id")]
        public int Id
        {
            set { id = value; }
            get { return id; }
        }

        [ManyToOne]
        public Address Address
        {
            set { address = value; }
            get { return address; }
        }
    }

    [Table("Address")]
    public class Address : IIdentifiable
    {
        private int id = -1;
        private string someFields = "";

        public Address() { }

        public Address(int id)
        {
            this.id = id;
        }

        [PrimaryKey, AutoIncrement, Column("_id")]
        public int Id
        {
            set { id = value; }
            get { return id; }
        }

        public string SomeFields
        {
            set { someFields = value; }
            get { return someFields; }
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire