上下文: 我們使用SQLite-Net Extensions
進行本地數據緩存,使用Xamarin
。我們計劃部署到iOS,Android和Windows Phone。我們在整個系統中都使用了現有的數據結構(都實現了一個通用接口),我們希望以這種方式進行存儲。如何將外鍵映射到SQLite-Net Extensions中的對象字段?
問題 作爲代碼示例中所示,[ManyToOne]
屬性用於表示的關係字段。這不起作用。如BitBucket Developer Page所述,[ForeignKey]
屬性可用於指定外鍵關係。這貌似只支持int
。我們是否可以輕鬆調整我們的結構以支持這些關係,而無需重複Id字段的屬性。例如以下是不可取的。
[ForeignKey(typeof(Address))]
public int AddressId { set; get; }
[ManyToOne]
public Address Address
{
set { address = value; }
get { return address; }
}
代碼示例
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; }
}
}
}
雖然這不是我們選擇的解決方案,但它是相似的。在我們的例子中,我們分叉了sqlite-net-extensions存儲庫並對其進行了修改。我們添加了一個新的自定義屬性來表示一個外鍵。然後,我們修改了內部讀/寫操作,以便每次檢測到該屬性時,都會寫入自定義關係表,存儲:源表,字段,對象標識和目標對象標識。 – TomTom