简体   繁体   English

SQLite-Net扩展| 相同实体的外键引用

[英]SQLite-Net Extensions | Foreign Key Reference to same entity

I am facing an issue in using SQLite-Net Extensions to save data in local DB in scenario where the foreign key is referencing the same entity (self-join). 在外键引用同一实体(自连接)的情况下,使用SQLite-Net扩展将数据保存到本地数据库中时遇到一个问题。

Example – Employee and Manager. 示例–员工和经理。 Every employee has a manager and a manager is also an employee. 每个员工都有一个经理,经理也是员工。 I am facing issues in saving data in such cases. 在这种情况下,我在保存数据时遇到了问题。 It will be really helpful if you can provide some insights. 如果您可以提供一些见解,那将非常有帮助。 Does this extension support this kind of relationship? 此扩展程序是否支持这种关系?

Yes, relationships between objects of the same class are supported, but the foreign keys and inverse properties must be explicitly specified in the relationship property attribute because the discovery system will get it wrong as there are be two relationships with the same type. 是的,支持相同类的对象之间的关系,但是必须在Relationship属性属性中显式指定外键和反向属性,因为发现系统会错误地发现它,因为存在两个相同类型的关系。

This example is extracted from the project readme: 此示例摘自项目自述文件:

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

As you can see here we have a many-to-many between Twitter users. 如您在这里看到的,我们在Twitter用户之间有很多对很多。 In your case it will be a one-to-many, so you won't need the intermediate table and you'll need the foreign key ( ManagerId for example) in your Person class. 在您的情况下,它将是一对多的,因此您不需要中间表,并且在Person类中需要外键(例如ManagerId )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM