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

我与影子孤独终老i 提交于 2019-12-11 06:19:24

问题


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 !


回答1:


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);


来源:https://stackoverflow.com/questions/41804732/create-and-select-from-a-table-dynamically-using-servicestack-ormlite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!