ServiceStack.OrmLite Create table with table name

1.4k Views Asked by At

I am using ServiceStack.OrmLite version 3.9.71 and I would like to create table with specific table name. So I want to have something similar to the following

db.CreateTable<TableType>("Table Name");

I have found the following relevant question but it looks like it is using a newer version.

Create table with custom name dynamically and insert with custom table name

1

There are 1 best solutions below

0
On BEST ANSWER

I have figured out how to do this. The v3 has method called GetModelDefinition which is doing the same as GetModelMetaData so I have modified the class inside the answer Create table with custom name dynamically and insert with custom table name.

The following is the final class that I am using

public static class GenericTableExtensions
{
    static object ExecWithAlias<T>(string table, Func<object> fn)
    {

        var modelDef = SqlServerOrmLiteDialectProvider.GetModelDefinition(typeof(T));
        lock (modelDef)
        {
            var hold = modelDef.Alias;
            try
            {
                modelDef.Alias = table;
                return fn();
            }
            finally
            {
                modelDef.Alias = hold;
            }
        }
    }
    public static void CreateTable<T>(this IDbConnection db, string table) where T: new()
    {
        ExecWithAlias<T>(table, () => { db.CreateTable<T>(); return null; });

    }

}