首页 > 解决方案 > Xamarin 表单 sql lite 表添加外键约束

问题描述

我的应用程序使用要添加外键约束的模型创建表。

这是基表:

public class BaseTable
{
    [PrimaryKey, AutoIncrement]
    public int ID { get; set; }
    public string Name { get; set; }
}

这是子表

public class ChildTable
{
    [ForeignKeyConstraint(BaseTable.ID, ID)]
    public int ID { get; set; }
    public string Name { get; set; }
}

在我的 App.xaml.cs 中,我正在创建数据库,如下所示:

database.CreateTable<BaseTable>();
database.CreateTable<ChildTable>();

对于这一行:

[ForeignKeyConstraint(BaseTable.ID, ID)]

我得到对象 ref 是必需的,这是有道理的,但是我想在模型子表中添加外键关系。

在此先感谢您提供有关如何完成此任务的任何建议

标签: sqlitexamarin

解决方案


安装 SQLiteNetExtensions 后,我能够执行以下操作来解决我的问题:

public class ChildTable
{
    [ForeignKey(typeof(BaseTable))]
    public int ID { get; set; }
    public string Name { get; set; }
}

然后更新了我的基表,如下所示:

public class BaseTable
{
    [PrimaryKey, AutoIncrement]
    public int ID { get; set; }
    public string Name { get; set; }
    [OneToMany(CascadeOperations = CascadeOperation.All)] 
    public List<ChildTable> ChildTables { get; set; }
}

推荐阅读