Search code examples
c#genericssqlite-netgeneric-type-parameters

Generic class method using SQLite-Net


I am trying to write a generic method to get the data from tables.

I am using sqlite-net ORM.

My methods compile well for delete:

public bool DeleteItem<T>(T NewItem)
{
    SQLiteConnection conn = new SQLiteConnection(GetConnection());
    var result = conn.Delete<T>(NewItem);

    //...
}

And

public void CreateTable<T>()
{
    SQLiteConnection conn = new SQLiteConnection(GetConnection());
    conn.CreateTable<T>();
    conn.Close();
}

But if I try to get Table data as list, I get a compile error at conn.Table:

T Must be a non-Abstract Type ....

Here is my code that does not want to compile:

public List<T> GetAllItems<T>(string SelTable)
{
    SQLiteConnection conn = new SQLiteConnection(GetConnection());
    List<T> MyItems = conn.Table<T>().ToList();
    conn.Close();
    return MyItems;
}

Solution

  • The definition of Table in SQLiteConnection is

    public TableQuery<T> Table<T>() where T : new();
    

    So you have to add type constraints:

    public bool DeleteItem<T>(T NewItem) where T : new()  // not required, but useful
    {
        SQLiteConnection conn = new SQLiteConnection("xx");
        var result = conn.Delete<T>(NewItem);
        return true;
    }
    public void CreateTable<T>() where T : new()          // not required, but useful
    {
        SQLiteConnection conn = new SQLiteConnection("xx");
        conn.CreateTable<T>();
        conn.Close();
    }
    public List<T> GetAllItems<T>(string SelTable) where T : new()
    {
        SQLiteConnection conn = new SQLiteConnection("xx");
        List<T> MyItems = conn.Table<T>().ToList();
        conn.Close();
        return MyItems;
    }