4

是否可以在使用 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 扩展两个实体之间的一对一和一对多关系

并以这些网站为灵感:

https://bitbucket.org/twincoders/sqlite-net-extensions/overview

https://bitbucket.org/twincoders/sqlite-net-extensions/src/65a1f8519347c40c948855cfc1a1d4d8bbcc8748/Tests/ReflectionExtensionsTests.cs?at=master&fileviewer=file-view-default

不幸的是,到目前为止还没有运气。甚至可能吗?

4

1 回答 1

5

是的,这完全有可能,不幸的是你不能依赖自动外键和反向关系发现,所以你需要手动指定它。

例如,对于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; }
}

如果您的外键在Handobject 中声明,则属性属性是等效的:

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; }
}

而逆属性,如果需要,必须在两端属性的inversePropertykey中指定: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; }
}
于 2015-09-24T09:23:53.403 回答