我正在使用sqlite-Net PCL和sqlite-Net扩展来开发使用Xamarin的应用程序.
在我的模型中,我有两个实体,让我们称它们为A和B,它们通过一对一和一对多的关系连接起来.例如,A与B具有一对一的关系,A与B具有一对多的关系.
是否可以用sqlite-Net扩展表达这种行为?
是的,但您必须在关系属性中显式声明外键和反向属性,否则库可能会获得该关系的错误外键.
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; } }
请注意,可以在任何类中声明OneToOne关系的外键O2OClassAKey.
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; } }