How to make SQLite foreign keys with SQLite.Net-PCL

detailCode picture detailCode · Apr 21, 2017 · Viewed 7.7k times · Source

In UWP, I enjoy the benefits of using SQLite.Net-PCL, creating classes to be used in apps as ObservableCollections to bind to the GridView. After including SQLiteNetExtensions to build a database with foreign keys, I've noticed that the foreign keys are not truly created when viewing the database in SQLite Maestro. Indexes are created instead. What is the benefit to using the SQLiteNetExtensions if it doesn't really create foreign keys?

Maybe foreign keys are not necessary (later in the app after the database is created) when querying with LAMDA expressions or LINQ. If I executed queries to create tables with foreign keys without using SQLite.Net-PCL, can I still use SQLite.Net-PCL to continue to bind ObservableCollections to GridViews?

Example Database:

[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 is new to me, and there are so many SQLite Nuget packages to choose from. Tutorials are a couple of years old, so there may be something better out now. Thanks in advance.

Answer

Ken Tucker picture Ken Tucker · Apr 22, 2017

Even if you used the entity framework core with the UWP app for your data access foreign keys are not available. By default foreign keys are not enabled in SQLite

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

https://sqlite.org/foreignkeys.html