Search code examples
c#listlitedb

Can I dynamically choose the type of a LiteCollection<T> in a method signature?


I have a custom class Customer and inside another class a method that returns a list based on a LiteCollection from LiteDB typized using the Customer class in the signature. What I wanted to know is if it’s possible creating a method that dynamically chooses which class uses a type, meaning if I can pass as a parameter the class type of the LiteCollection to return when I call the method.

The code is as follows:

public static LiteCollection<Customer> GetCustomers()
        {
            var collection = ConnectToDB().GetCollection<Customer>("customers");

            return collection;
        }

Solution

  • How about:

    public static LiteCollection<T> Get(string tableName)
    {
        return ConnectToDB().GetCollection<T>(tableName);
    }
    

    That would be called:

    var table = Get<Customer>("customers");
    

    Update

    Unfortunately it is not really possible to get rid of the generic type, cause otherwise your consuming code doesn't know what it gets back. So the minimum that would be possible would be

    var table = Get<Customer>();
    

    In that case your implementation needs some kind of mapper from type to table name. For this purpose I could think of three possibilities (which you could also combine):

    • The class has an internal Dictionary<Type, string> where all table names for a given type is manually entered.
    • The convention is that for every T the table name is a pluralized string of the type name, then you need a pluralize method that returns Pluralize(typeof(T).Name).
    • By reflection you iterate over your derived DBContext, get out all DBSet<> properties and pre-fill the dictionary out of the first possibility by using the generic argument from DBSet<> and the property name.