使用SQLiteAsyncConnection在SQLite-net C#中创建通用查询

前端之家收集整理的这篇文章主要介绍了使用SQLiteAsyncConnection在SQLite-net C#中创建通用查询前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用sqlite-net( https://github.com/praeclarum/sqlite-net)在Android上使用Mono实现数据库并具有以下功能

public class DatabaseTestASync
{
    private sqliteAsyncConnection m_db;

    public delegate void StocksFound(List<Stock> list);
    public event StocksFound StocksFoundListener;

    // Uninteresting parts remove,e.g. constructor

    public void AddStock(Stock stock)
    {
        m_db.InsertAsync(stock).ContinueWith(t => { Debug.WriteLine(stock.Symbol + " added"); });
    }

    public void GetAllStocks()
    {
        AsyncTableQuery<Stock> query = m_db.Table<Stock>().Where(stock => true);
        query.ToListAsync().ContinueWith(QueryReturns);
    }

    private void QueryReturns(Task<List<Stock>> t)
    {
        if (StocksFoundListener != null)
            StocksFoundListener(t.Result);
    }

这非常适合给我一个股票列表,但我设想在我的项目中有一个表集合,并且不想为每个表创建单独的AddX,GetAllX,QueryReturns(X)等.我正在执行这些数据库操作的通用方法并尝试以下方法

public class DBQuery<T>
{
    private sqliteAsyncConnection m_db;
    public delegate void OnRecordsFound(List<T> list);
    public event OnRecordsFound RecordsFoundListener;

    public DBQuery (sqliteAsyncConnection db)
    {
        m_db = db;
    }

    public void GetAllRecords()
    {
        AsyncTableQuery<T> query = m_db.Table<T>().Where(r => true); // COMPILE ERROR HERE
        query.ToListAsync().ContinueWith(QueryReturns);
    }

    private void QueryReturns(Task<List<T>> t)
    {
        if (RecordsFoundListener != null)
            RecordsFoundListener(t.Result);
    }
}

但是,它没有编译说:’T’必须是具有公共无参数构造函数的非抽象类型,以便在泛型类型或方法’DatabaseUtility.AsyncTableQuery’中将其用作参数’T’.

关于如何让这种通用数据库访问工作的任何想法?

解决方法

我真的不知道sqlite内部,但这完全是关于泛型…

因为AsyncTableQuery是这样定义的

public class AsyncTableQuery<T>
        where T : new ()
    {

…或者只是根据你的错误,你需要在你的T上加上相同的约束:

public class DBQuery<T> where T : new ()

If you’re using a class or a method which has a constrained generic
parameter
– you need to do the same on your method (or a class,
depending on where the T is defined).

猜你在找的Sqlite相关文章