我正在使用SQLite-Net PCL和SQLite-Net扩展来使用Xamarin开发应用程序。
在我的模型中,我有两个实体,我们分别称为A和B,它们通过一对一和一对多的关系相连。例如,A与B具有一对一的关系,A与B也具有一对多的关系。
是否可以使用SQLite-Net扩展来表达这种行为?
是的,但是您必须在Relationship属性中显式声明外键和逆属性,因为否则库可能会为该关系获取错误的外键。
public class ClassA
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[OneToMany("O2MClassAKey", "BObjectsInverse")]
public List<ClassB> BObjects { get; set; }
[OneToOne("O2OClassAKey", "BObjectInverse")]
public ClassB BObject { get; set; }
// Other properties
public string Bar { get; set; }
}
public class ClassB
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[ForeignKey(typeof (ClassA))]
public int O2MClassAKey { get; set; }
[ForeignKey(typeof (ClassA))]
public int O2OClassAKey { get; set; }
// Inverse relationships, these are optional
[ManyToOne("O2MClassAKey", "BObjects")]
public ClassA BObjectsInverse { get; set; }
[OneToOne("O2OClassAKey", "BObject")]
public ClassA BObjectInverse { get; set; }
// Other properties
public string Foo { get; set; }
}
请注意,可以在任何类中声明O2OClassAKey
该OneToOne
关系的外键。
如果不需要逆属性,则可以在Relationship属性中跳过它们:
public class ClassA
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[OneToMany("O2MClassAKey")]
public List<ClassB> BObjects { get; set; }
[OneToOne("O2OClassAKey")]
public ClassB BObject { get; set; }
// Other properties
public string Bar { get; set; }
}
public class ClassB
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[ForeignKey(typeof (ClassA))]
public int O2MClassAKey { get; set; }
[ForeignKey(typeof (ClassA))]
public int O2OClassAKey { get; set; }
// Other properties
public string Foo { get; set; }
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句