Search code examples
c#sqlitesimplification

Remove redundancies with multiple object types


I have a function that selects some properties from an SQLite query. This function returns e.g. a static List<Requests>. It works perfectly, the only problem is that I need this function to operate on many different objects, like cnn.Query<Requests>, cnn.Query<Responses>, and so on. So I dont want to call this function 20 times for 20 different objects.

Can someone show me please how I can make these <Requests> or <Responses> dynamic to just call the function one single time?

Two times nearly the same function that I want to reduce to one:

public static List<Requests> ReadRequests(SQLiteCommand command)
        {
            using (IDbConnection cnn = new SQLiteConnection(command.Connection))
            {
                var output = cnn.Query<Requests>("select * from Requests", new DynamicParameters());
                return output.ToList();
            }
        }
        public static List<Responses> ReadResponses(SQLiteCommand command)
        {
            using (IDbConnection cnn = new SQLiteConnection(command.Connection))
            {
                var output = cnn.Query<Responses>("select * from Requests", new DynamicParameters());
                return output.ToList();
            }
        }

Solution

  • What you can do is to make a generic class (refer to the tutorial here http://dotnetpattern.com/csharp-generics). You still need to build & call the class everytime though.

    e.g.:

    public class GenericClass<T>
    {
        public  List<T> ReadT(SQLiteCommand command)
        {
            using (IDbConnection cnn = new SQLiteConnection(command.Connection))
            {
                var output = cnn.Query<T>("select * from "+typeof(T).Name, new DynamicParameters());
                return output.ToList();
            }
        }
    }
    

    P.S. Haven't tested the code, so just use it as a reference.