哪种方法可以将多个一对一关系建模到同一个表(sqlite-net-extensions)?我正在寻找这样的解决方案:
Class WayBill
{
[PrimaryKey, AutoIncrement]
public int Id {get; set;}
[ForeignKey(typeof(Organization ))]
public int ConsignerId {get; set;}
[OneToOne]
public Organization Consigner {get; set;}
[ForeignKey(typeof(Organization ))]
public int ConsigneeId {get; set;}
[OneToOne]
public Organization Consignee {get; set;}
}
Class Organization
{
[PrimaryKey, AutoIncrement]
public int Id {get; set;}
public string Name {get; set;}
}
显然,上述不会奏效。
我也考虑了其他选择:
创建一个捕获组织角色的表(WayBillOrganization): 运单 - >> WayBillOrganization - >组织
将所需的反向OneToMany属性放入组织。
手动处理事物(即仅在WayBill类中存储主键并单独加载组织)。
选项2.是我想要避免的。组织与许多其他课程(不是我的例子)有关,甚至在运单的情况下,还有更多的关系,我没有包括在这个例子中(承运人,货运支付方,货运代理人)等等)。此外,我只是在我需要导航时才使用逆属性(例如,我不使用组织来查找运单,因此反向属性只是额外的负担。)
选项3.也不具吸引力。
所以选项1.似乎是要走的路。但在去那里之前,我想知道我的例子中的完美世界解决方案是否确实不可能。
所以,我的问题是:有没有办法模拟多个一个方向 OneToOne关系而没有显式声明反向属性?
答案 0 :(得分:4)
SQLite-Net Extensions支持您的用例。您只需在关系属性中明确指定外键,因为自动发现可能无法按预期工作:
class WayBill
{
[PrimaryKey, AutoIncrement]
public int Id {get; set;}
public int ConsignerId {get; set;}
[OneToOne("ConsignerId")]
public Organization Consigner {get; set;}
public int ConsigneeId {get; set;}
[OneToOne("ConsigneeId")]
public Organization Consignee {get; set;}
}
class Organization
{
[PrimaryKey, AutoIncrement]
public int Id {get; set;}
public string Name {get; set;}
}
也支持与同一个类的反向关系,但也必须在两端明确声明:
class WayBill
{
[PrimaryKey, AutoIncrement]
public int Id {get; set;}
public int ConsignerId {get; set;}
[OneToOne(foreignKey: "ConsignerId", inverseProperty: "ConsignerInverse")]
public Organization Consigner {get; set;}
public int ConsigneeId {get; set;}
[OneToOne(foreignKey: "ConsigneeId", inverseProperty: "ConsigneeInverse")]
public Organization Consignee {get; set;}
}
class Organization
{
[PrimaryKey, AutoIncrement]
public int Id {get; set;}
public string Name {get; set;}
[OneToOne(foreignKey: "ConsigneeId", inverseProperty: "Consignee")]
public WayBill ConsigneeInverse { get; set; }
[OneToOne(foreignKey: "ConsignerId", inverseProperty: "Consigner")]
public WayBill ConsignerInverse { get; set; }
}