【问题标题】:SQLite-Net Extensions | Foreign Key Reference to same entitySQLite-Net 扩展 |对同一实体的外键引用
【发布时间】:2018-11-18 09:47:21
【问题描述】:

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

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

【问题讨论】:

    标签: sqlite xamarin.forms crud sqlite-net


    【解决方案1】:

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

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

    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 用户之间存在多对多。在您的情况下,它将是一对多的,因此您不需要中间表,并且您需要 Person 类中的外键(例如 ManagerId)。

    【讨论】:

      猜你喜欢
      • 2015-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-17
      相关资源
      最近更新 更多