Question

I created a property class representing the table schema of my SQLite database. Each attribute in the class become one attribute in the database.

class SQLiteTables
{
    public class tblPerson
    {
        [PrimaryKey, AutoIncrement]
        public int PersonID { get; set; }
        public string PersonFirstName { get; set; }
        public string PersonMiddleName { get; set; }
        public string PersonLastName { get; set; }
    }

    public class tblSchedule
    {
        [PrimaryKey, AutoIncrement]
        public int ScheduleID { get; set; }
        public string ScheduleDescription { get; set; }
        public DateTime ScheduleStart { get; set; }
        public DateTime ScheduleEnd { get; set; }
    }

    //18 more table definitions below
}

Now, to retrieve some data from a table,

public void GetPersonList()
{
    List<tblPerson> lstTemp = dbConn.Table<tblPerson>().ToList<tblPerson>();

    // Some 20 lines of code here
}

I want to avoid writing type-specific methods, well it's kind of a tedious task. I want to create a reusable method which can retrieve data on any table using generics implementation. How can I achieve this?

EDIT I am working on a Windows Phone 8 platform.

Was it helpful?

Solution

This should work for what you're doing.

public List<T> GetItems<T>()
{
    return dbConn.Table<T>().ToList<T>();
}

OTHER TIPS

You could use DBLinq, which has support for SQLite - then you get your syntax for free on the data context.

 public IList<T> GetList<T>()
 {
     return _context.GetTable<T>().ToList();
 }
public IEnumerable<T> GetItems<T>() where T: new()
    {
        lock (locker) {
            return dbCon.Table<T> ().ToArray ();
        }
    }

I think the key is the ":new()" at the end

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top