Search code examples
c#sqlitegenericsinterfacecreate-table

Does SQLite .NET Accept interfaces in the CreateTable Method


At the moment I am trying to create a generic class to create a table that can either take a class or an interface as T. Here is what I have so far:

public class MobileDataBase<T> where T : new()
{
    SQLiteConnection database;

    public MobileDataBase()
    {
        database.CreateTable<T>();
    }
}

This works fine when I feed a class into it like so:

MobileDataBase<MyClass> database = new MobileDataBase<MyClass>();

But gives me the error:

Must be non-abstract type with a public parameterless constructor in order to use it as parameter T in the generic type or method

if I give it the arguments

MobileDataBase<IMyInterface> database = new MobileDataBase<IMyInterface>();

The reason I use an interface is because I have two objects that inherit this interface and I would like to store their information in the same table rather than two seperate ones...

I also want to use the generic class MobileDataBase for other classes that do not inherit from IMyInterface therefore:

public class MobileDataBase<T> where T : IMyInterface

is not a solution


Solution

  • Heres a solution to this problem:

    So MyClass : IMyInterface but the problem comes when I try to feed the interface IMyInterface into my generic method which in turn calls CreateTable<T>()

    So This is what I did. I created a base class called MyBaseClass And implemented that instead of the interface..

    MyClass : MyBaseClass
    

    Now I can pass MyBaseClass into the generic method no problem. If you still want to use the interface you can make MyBaseClass implenet the Interface like so:

    MyBaseClass : IMyInterface
    

    in addition to this when using the

    database.Insert(object, type)
    

    use it like

    database.Insert(MyClass,typeof(MyBaseClass)