是否可以使用SQLite.Net.Async Extensions PCL 1.3.0在实体中拥有多个OneToOne关系?
示例:
[Table("body")]
public class Body
{
[OneToOne(CascadeOperations = CascadeOperation.All)]
[Column ("left")]
public Hand Left { get; set; }
[OneToOne(CascadeOperations = CascadeOperation.All)]
[Column ("right")]
public Hand Right { get; set; }
}
[Table("hand")]
public class Hand
{
// In this I do not need a reference back to Body.
}
我一直在尝试使用以下答案:
SQLite-Net Extension both one-to-one and one-to-many relationships between two entities
并以这些网站为灵感:
https://bitbucket.org/twincoders/sqlite-net-extensions/overview
遗憾的是到目前为止没有运气。它甚至可能吗?
答案 0 :(得分:4)
是的,这完全有可能,不幸的是你不能依赖自动外键和反向关系发现,所以你需要手动指定它。
例如,对于int
主键和在同一类中声明的外键:
public class Body
{
[OneToOne(foreignKey: "LeftId", CascadeOperations = CascadeOperation.All)]
public Hand Left { get; set; }
[OneToOne(foreignKey: "RightId", CascadeOperations = CascadeOperation.All)]
public Hand Right { get; set; }
// Foreign key for Left.Id
public int LeftId { get; set; }
// Foreign key for Right.Id
public int RightId { get; set; }
}
public class Hand
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
}
如果在Hand
对象中声明了外键,则属性属性是等效的:
public class Body
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[OneToOne(foreignKey: "LeftId", CascadeOperations = CascadeOperation.All)]
public Hand Left { get; set; }
[OneToOne(foreignKey: "RightId", CascadeOperations = CascadeOperation.All)]
public Hand Right { get; set; }
}
public class Hand
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
// Foreign key for Body.Id where this object is Left
public int LeftId { get; set; }
// Foreign key for Body.Id where this object is Right
public int RightId { get; set; }
}
如果需要,必须在两端的inverseProperty
属性的OneToOne
键中指定反向属性:
public class Body
{
// Skipping foreign keys and primary key
[OneToOne(foreignKey: "LeftId", inverseProperty: "LeftBody", CascadeOperations = CascadeOperation.All)]
public Hand Left { get; set; }
[OneToOne(foreignKey: "RightId", inverseProperty: "RightBody", CascadeOperations = CascadeOperation.All)]
public Hand Right { get; set; }
}
public class Hand
{
// Skipping foreign keys and primary key
[OneToOne(foreignKey: "LeftId", inverseProperty: "Left", CascadeOperations = CascadeOperation.All)]
public Body LeftBody { get; set; }
[OneToOne(foreignKey: "RightId", inverseProperty: "Right", CascadeOperations = CascadeOperation.All)]
public Body RightBody { get; set; }
}