上下文
我们使用SQLite-Net Extensions
将Xamarin
用于本地数据缓存。我们计划部署到iOS,Android和Windows Phone。我们在整个系统中使用现有的数据结构(都实现了一个通用接口),我们希望以这种方式存储。
问题
如代码示例所示,[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; }
}
}
}
答案 0 :(得分:1)
SQLite-Net Extensions是SQLite-Net上的一个薄层,它使用sqlite数据库进行存储。关系数据库使用外键存储关系,sqlite在这方面没有什么不同。因此,SQLite-Net和SQLite-Net Extensions也使用外键机制来声明关系。
作为替代方案,您可以使用中间表来存储关系,与ManyToMany
关系的工作方式相同,但将其中一个端点限制为一个。这样您就可以使用ManyToMany关系和中间表来模仿OneToMany
,ManyToOne
甚至OneToOne
关系。例如:
[Table("Client")]
public class Client {
[PrimaryKey, AutoIncrement, Column("_id")]
public int Id { get; set; }
[Ignore] // This property shouldn't be persisted
public Address Address { get; set; }
// This relationship is in fact a ManyToOne relationship,
// but we model it as a ManyToMany to avoid adding foreign key to this entity
[ManyToMany(typeof(AddressesClients))]
public Address[] Addresses {
get { return Address != null ? new []{ Address } : Address; }
set { Address = value.FirstOrDefault(); }
}
}
[Table("Address")]
public class Address
{
[PrimaryKey, AutoIncrement, Column("_id")]
public int Id { get; set; }
public string SomeFields { get; set; }
[ManyToMany(typeof(AddressesClients), ReadOnly = true)]
public List<Client> Clients { get; set; }
}
// Intermediate table that defines the relationship between Address and Client
class AddressesClients {
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[ForeignKey(typeof(Client))]
public int ClientId { get; set; }
[ForeignKey(typeof(Address))]
public int AddressId { get; set; }
}
当然,这会有一些性能损失。
至于PrimaryKey
,您可以使用任何支持的类型,并且必须使用相反的ForeignKey
完全相同的类型,即如果您使用Guid
作为主键, 指向到该类的外键也必须是Guid
。在演示项目中,我们已经使用int
(性能最高),string
甚至UUID
。