Query multiple tables SQLite Windows 10 UWP

坚强是说给别人听的谎言 提交于 2019-12-13 16:38:32

问题


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.



来源:https://stackoverflow.com/questions/34850610/query-multiple-tables-sqlite-windows-10-uwp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!