0

I want to make a dynamic get-query for my project (with C#). I have imported some SQLite code, and I basically want to turn this function:

    public static MyModel GetModel(string id)
    {
          using (var db = new SQLiteConnection(GetDbPath()))
          {
              return (from s in db.Table<MyModel>() where s.Id.Equals(id) select s).FirstOrDefault();
          }
    }

into this:

    public static object Get(object item, string id)
    {
          using (var db = new SQLiteConnection(GetDbPath()))
          {
              return (from s in db.Table<item.GetType()>() where s.Id.Equals(id) select s).FirstOrDefault();
          }
    }

This gives me two challenges. First I need to somehow tell the db.Table<> that I want to use whatever type "item" is. Secondly, I will guarantee the code that whatever object "item" is, it has an "Id" member. I have tried to look at similar questions, and I have found this which I have tried to implement, but I am not sure if this question and mine is the same.

Is this possible?

Community
  • 1
  • 1
mathkid91
  • 659
  • 2
  • 10
  • 27
  • Why are you trying to do it dynamically? Are you creating tables dynamically? Why not just implement a Generic Repository pattern? – Robert McKee Nov 14 '16 at 18:18
  • Yes, the SQLiteConnection file (a class I have copy-pasted from SQLite for Xamarin) creates the tables dynamically, based on the type of object, for example table for MyModel. Edit: I Googled Generic Repository Pattern, and this looks like what I am trying to make. I will read up on this. – mathkid91 Nov 14 '16 at 22:53

0 Answers0