-1

I'm creating a synchronize function between a device and server for a large database. I have a lot of listing tables (the items in a dropdown/picker). I don't want to write a lot of code and I'm looking for an elegant solution :)

On a device in SQLite I defined listing table like

    public class NameTable : IBusinessEntity {
        public int Id { get; set; } = 0;
        public string Description { get; set; }
    }

When I save in database a new record (item) I call this function

    public int SaveItem<T>(T item) where T : IBusinessEntity {
        lock (locker) {
            if (item.Id != 0) {
                database.Update(item);
                return item.Id;
            }
            else {
                return database.Insert(item);
            }
        }
    }

Now when the device receives a new record from the server the structure is like

    public class SyncResult {
        public int DeviceId { get; set; }
        public int ServerId { get; set; }
        public string TableName { get; set; }
        public string Description { get; set; }
    }

Then I want to save (insert a new record if DeviceId == 0 or update an existing item).

My question is: how can I call SaveItem where T is the TableName from SyncResult?

Thank you in advance for any help (I can offer a beer for that!)


SaveItem is a member of MyDatabase class. Basically my problem is how to pass to SaveItem<T> the T as string.

I don't know if I explained clearly my issue.

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
Enrico
  • 3,592
  • 6
  • 45
  • 102

1 Answers1

0

You could map a TableName to a Type for example Dictionary<string,Type> Use the Activator class to construct the type. Use reflection to fill the data.

Jeroen van Langen
  • 21,446
  • 3
  • 42
  • 57
  • Thanks. When I invoke an `Activator`, can I receive something in return? For example to update a record I have to read the current record and the update it. – Enrico Sep 06 '16 at 10:16
  • And I can select GetMethod or GetMethodRuntime or something else? – Enrico Sep 06 '16 at 10:21
  • If you inherit all Types from `IBusinessEntity`. You can cast it to `IBusinessEntity` for example: `IBusinessEntity myObj = (IBusinessEntity)Activator.Create(typeNameStr)` You might move something like the `SaveItem` method to the Interface. – Jeroen van Langen Sep 06 '16 at 11:03