【发布时间】:2021-01-13 01:02:13
【问题描述】:
我在我的项目中使用sqlite-net 并有一个名为 SqLiteHelper 的帮助程序类。在这个类中,我有一个简单的方法,它以列表的形式返回TableQuery 结果。
示例:
public static class SqLiteHelper
{
public static List<Contact> GetTableQueryResults()
{
List<Contact> contacts;
using (var connection = new SQLiteConnection(App.DatabasePath))
{
connection.CreateTable<Contact>();
contacts = connection.Table<Contact>().ToList();
}
return contacts;
}
}
我想让这个方法可重复使用,以便将来在其他上下文中使用它。例如,当我将有另一个具有不同类的项目时,然后是“联系”。我自己尝试过,将其重构为:
public static IList<T> GetTableQueryResults<T>()
{
List<T> contacts;
using (var connection = new SQLiteConnection(App.DatabasePath))
{
connection.CreateTable<T>();
contacts = connection.Table<T>().ToList();
}
return contacts;
}
但是 SQLiteConnection.Table 方法会抛出以下错误:
有什么想法可以使这种方法可重复使用吗?
我看过here 但它与SQLite 无关。
【问题讨论】:
-
数据库连接不应该被重用。在尽可能小的范围内创建、使用和处置它们。 DB Provider 实现了连接池来提高效率。里面有很多文档。
-
@ŇɏssaPøngjǣrdenlarp 数据库连接没有在这里重用..它是在 using 块中创建的,将被处理。我怀疑 OP 意味着您可以将泛型类型传递给的方法可重用。
-
@BrettCaswell 是的,这就是我想要实现的目标。看起来下面我的问题得到了使用
new constraint的回答。