加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-12 18:57:29 所属栏目:百科 来源:网络整理
导读:我正在使用SQLite-net( https://github.com/praeclarum/sqlite-net)在Android上使用Mono实现数据库并具有以下功能: public class DatabaseTestASync{ private SQLiteAsyncConnection m_db; public delegate void StocksFound(ListStock list); public event
我正在使用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).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读