Query multiple tables SQLite Windows 10 UWP

2019-07-09 09:52发布

问题:

I am developing a Windows 10 UWP app with a SQLite database. I need to retrieve data from multiple tables. I already have the following code to get data from a single table, but a custom object with the exact same amount and names of the columns of the table in question is needed.

public ObservableCollection<Employee> GetEmployees()
{
    using (var dbConn = new SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.DB_PATH))
    {
        List<Employee> myCollection = dbConn.Table<Employee>().ToList<Employee>();
        ObservableCollection<Employee> EmployeesList = new ObservableCollection<Employee>(myCollection);
        return EmployeesList;
    }
}

I also know that it is possible to query a table using the following code, but still only from a single table.

public ObservableCollection<Question> GetQuestionsForAssessment(int assessment_id)
{
    using (var dbConn = new SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.DB_PATH))
    {
        List<Question> myCollection = dbConn.Query<Question>("select * from Question where AssessmentId = ?", assessment_id);
        ObservableCollection<Question> QuestionsList = new ObservableCollection<Question>(myCollection);
        return QuestionsList;
    }
}

So does anybody know how I can query from multiple tables? Thanks

回答1:

There's nothing preventing you from writing queries with joins:

using (var db = new SQLiteConnection(new SQLitePlatformWinRT(), App.DB_PATH))
{
    var result = db.Query<PersonWithAddress>(
        @"SELECT Person.Id, Person.Name, Person.Surname, 
            Address.Street, Address.City, Address.Country
        FROM Person INNER JOIN Address ON Person.AddressId = Address.Id;");
}

You do need to have a class with fields from multiple tables to map the result into:

private class PersonWithAddress
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public string Street { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
}

Alternatively you could try out SQLite-Net Extensions which adds support for relationships between entities. I've never used it, though.