Home > OS >  How to use generic with SQLite
How to use generic with SQLite

Time:08-09

I created a class called DB_Processor_Generic, which is used to create different database and do add/get data operations. But I need to use this class with different data types, so I consider using generic, but when I use the "_db.Query()" as shown below, I get the error saying that

'T' must be a non-abstract type with a public parameterless construction in order to use it as parameter 'T' in the generic type or method 'SQLiteConnection.Query(string, params object[])

Is there anything wrong with my code? Cause I am new to this community, if there is anything wrong with my question discription, plz correct me thanks

    public class DB_Processor_Generic<T>
    {
        private SQLite.SQLiteConnection _db;
        private string _path;

        //Constructor
        public DB_Processor_Generic(string path)
        {
            _path = path;
            _db = new SQLite.SQLiteConnection(this._path);
            _db.CreateTable<T>();
        }

        //Method
        public void AddData<T>(T t1)
        {
            _db.Insert(t1);
        }

        public List<T> GetDB<T>(string tableName)
        {
            var DB_List = _db.Query<T>($"SELECT * FROM {tableName}");
            return DB_List;
        }
    }

CodePudding user response:

That error tells you you need to add a constraint to your T:

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

because Query<T> has that constraint on T in it's definition, so yours must be set as well in order to use your T as it's type parameter.

  • Related