如何使用SQLite.Net-PCL制作SQLite外键

时间:2017-04-21 21:00:21

标签: c# uwp sqlite-net sqlite-net-extensions

在UWP中,我喜欢使用SQLite.Net-PCL的好处,创建要在应用程序中使用的类作为ObservableCollections绑定到GridView。在包含SQLiteNetExtensions以使用外键构建数据库之后,我注意到在SQLite Maestro中查看数据库时并未真正创建外键。而是创建索引。 如果没有真正创建外键,使用SQLiteNetExtensions会有什么好处?

在使用LAMDA表达式或LINQ查询时,可能不需要外键(在创建数据库后的应用程序中)。 如果我执行查询以使用外键创建表而不使用SQLite.Net-PCL,我是否仍然可以使用SQLite.Net-PCL继续将ObservableCollections绑定到GridViews?

示例数据库:

[Table("Book")]
public class Book
{
    [PrimaryKey, AutoIncrement, Column("ID")]
    public int ID { get; set; }
    [Column("Name")]
    public string Name { get; set; }

    [ManyToMany]
    public List<Checkout> Checkout { get; set; }
}

[Table("School")]
public class School
{
    [PrimaryKey, AutoIncrement, Column("ID")]
    public int ID { get; set; }
    [Column("Name")]
    public string Name { get; set; }

    [OneToMany]
    public List<Student> Student { get; set; }
    [ManyToMany]
    public List<Checkout> Checkout { get; set; }
}

[Table("Student")]
public class Student
{
    [PrimaryKey, AutoIncrement, Column("ID")]
    public int ID { get; set; }
    [Column("SchoolID"), ForeignKey(typeof(School))]
    public int SchoolID { get; set; }
    [Column("Name")]
    public string Name { get; set; }

    [ManyToOne]
    public School School { get; set; }
}

[Table("Checkout")]
public class Checkout
{
    [PrimaryKey, AutoIncrement, Column("ID")]
    public int ID { get; set; }
    [Column("SchoolID"), ForeignKey(typeof(School))]
    public int SchoolID { get; set; }
    [Column("BookID"), ForeignKey(typeof(Book))]
    public int BookID { get; set; }
}

SQLite对我来说是新手,有很多SQLite Nuget包可供选择。教程已经有几年了,所以现在可能会有更好的东西。提前谢谢。

2 个答案:

答案 0 :(得分:1)

即使您将实体框架核心与UWP应用程序一起用于数据访问,外键也不可用。默认情况下,SQLite

中未启用外键

https://docs.microsoft.com/en-us/ef/core/providers/sqlite/limitations

https://sqlite.org/foreignkeys.html

答案 1 :(得分:0)

你在官方网站上有example如何在SQLite中使用外键。

相关问题