【问题标题】:Query multiple tables SQLite Windows 10 UWP查询多个表 SQLite Windows 10 UWP
【发布时间】:2016-04-23 09:08:39
【问题描述】:

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

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

我也知道可以使用以下代码查询表,但仍只能从单个表中查询。

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

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

【问题讨论】:

  • 你能解释一下你到底要做什么吗?它是一个 Employee 对象,它的属性存储在另一个表中?你要加盟吗?问候!
  • 您使用的 SQLite 库是什么?是 SQLite.Net-PCL 吗?

标签: c# sqlite uwp windows-10-universal sqlite-net


【解决方案1】:

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

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

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

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,它增加了对实体之间关系的支持。不过我没用过。

【讨论】:

    猜你喜欢
    • 2017-07-30
    • 2016-09-03
    • 2017-02-03
    • 2016-01-24
    • 1970-01-01
    • 2015-11-04
    • 2016-10-27
    • 2021-08-01
    • 1970-01-01
    相关资源
    最近更新 更多