首页 > 解决方案 > SQLite-Net 扩展 | 对同一实体的外键引用

问题描述

在外键引用同一实体(自联接)的情况下,我在使用 SQLite-Net 扩展将数据保存在本地数据库中时遇到问题。

示例——员工和经理。每个员工都有一个经理,一个经理也是一个员工。在这种情况下,我在保存数据时遇到了问题。如果您能提供一些见解,那将非常有帮助。这个扩展是否支持这种关系?

标签: sqlitexamarin.formscrudsqlite-net

解决方案


是的,支持同一类的对象之间的关系,但是必须在关系属性属性中明确指定外键和反向属性,因为发现系统会出错,因为存在两个具有相同类型的关系。

此示例摘自项目自述文件:

public class TwitterUser {
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }

    public string Name { get; set; }

    [ManyToMany(typeof(FollowerLeaderRelationshipTable), "LeaderId", "Followers",
        CascadeOperations = CascadeOperation.CascadeRead)]
    public List<TwitterUser> FollowingUsers { get; set; }

    // ReadOnly is required because we're not specifying the followers manually, but want to obtain them from database
    [ManyToMany(typeof(FollowerLeaderRelationshipTable), "FollowerId", "FollowingUsers",
        CascadeOperations = CascadeOperation.CascadeRead, ReadOnly = true)]
    public List<TwitterUser> Followers { get; set; }
}

// Intermediate class, not used directly anywhere in the code, only in ManyToMany attributes and table creation
public class FollowerLeaderRelationshipTable {
    public int LeaderId { get; set; }
    public int FollowerId { get; set; }
}

正如您在此处看到的,我们在 Twitter 用户之间存在多对多。在您的情况下,它将是一对多的,因此您不需要中间表,并且您需要类中的外键(ManagerId例如)Person


推荐阅读