Search code examples
c#sql-serverormlite-servicestack

Create (and select from) a table dynamically using servicestack ormlite


I am using C#, and I try to create a table, using ServiceStack.OrmLite, corresponding to a class type created in run-time, I searched for the topic and I have found the following solution:

  • After creating the type in runtime (employeeType), I could do the following:

    db.CreateTableIfNotExists(employeeType);
    

This would create the table Employee corresponding to the (dynamically created type "Employee")

  • Then, by using the following:

    var typedApi = db.CreateTypedApi(employeeType);
    

I could get a TypedApi which could be used to insert, delete, update the Employee table created dynamically.

  • In fact, my problem is that I cannot make a simple select statement from the table "Employee" because that requires to pass a generic type T which I don't have, as follows:

    db.Select<T>(); // T is supposed to be my "employeeType" created  dynamically.
    

Is it possible to make a select from a table corresponding to a run-time created type ?

Thank you for your help !


Solution

  • OrmLite APIs and SqlExpression are Typed, but you can execute Custom SQL for your runtime Type, e.g:

    var modelDef = employeeType.GetModelMetadata();
    var tableName = db.GetDialectProvider().GetQuotedTableName(modelDef);
    var sql = $"SELECT * FROM {tableName}";
    

    Which you can then Select using one of the dynamic result set APIs, e.g:

    var results = db.Select<List<object>>(sql);
    var results = db.Select<Dictionary<string,object>>(sql);
    var results = db.Select<dynamic>(sql);