查询多个表 SQLite Windows 10 UWP

Query multiple tables SQLite Windows 10 UWP

我正在使用 SQLite 数据库开发 Windows 10 UWP 应用程序。我需要从多个 table 中检索数据。我已经有以下代码从单个 table 获取数据,但是需要一个自定义对象,其数量和名称与所讨论的 table 的列完全相同。

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;
    }
}

我也知道可以使用以下代码查询 table,但仍然只能从单个 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;
    }
}

那么有人知道我如何从多个 table 中查询吗?谢谢

没有什么可以阻止您使用连接编写查询:

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;");
}

您确实需要 class 包含来自多个表的字段才能将结果映射到:

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; }
}

或者您可以尝试 SQLite-Net Extensions,它增加了对实体之间关系的支持。不过我从来没有用过它。