Xamarin SQLite.NET 通用表查询

Xamarin SQLite.NET Generic TableQuery

我在我的 Xamarin 项目中使用组件 "SQLite.NET"。 我有几个 "models/classes",例如 "Document"、"Project"。 每个模型在 SQLite 中都有自己的 Table。

为了从 table 获取数据,我使用了以下技术:

List<Document> documents = new SQLiteConnection("..DB-path..").Table<Document>.ToList();

它工作正常,但对于每个 table 我必须执行相同的代码并且只更改上面代码中的模型类型。

现在我想写一个通用方法,我可以这样做:

List<T> data = new SQLiteConnection("..DB-path..").Table<T>.ToList();

但不幸的是,我收到以下错误:

'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'SQLiteConnection.Table()'

有谁知道为上述问题创建通用方法的方法吗?

提前致谢!

你应该给你的函数添加约束。

public List<T> GetData<T> () where T: new()
{
    using(var connection = new SQLiteConnection("..DB-path..")){
       return connection.Table<T>.ToList();
    }
}

不要忘记释放你的数据库连接!