Search code examples
c#.netormservicestackormlite-servicestack

Get table name of class at runtime in ServiceStack.OrmLite / avoid hardcoding table names


I use ServiceStack.OrmLite and want to get the total count of rows from a table. I currently do as pointed out in the ServiceStack.OrmLite documentation via

db.Scalar<int>("SELECT COUNT(*) FROM User");

However, the table's name User might change in the future so I am looking for a way not to hardcode it. Is it possible to get the table's name from its according class, like i.e.

string table_name = db.GetTableName<User> ();
db.Scalar<int>("SELECT COUNT(*) FROM {0}", table_name);

?


Solution

  • The 2 ways to access the config metadata of your types is with:

    ModelDefinition<User>.Definition.ModelName;
    typeof(User).GetModelMetadata().ModelName;
    

    Although in some databases you need to quote your table name, you can do this with:

    var modelDef = ModelDefinition<User>.Definition;
    OrmLiteConfig.DialectProvider.GetQuotedTableName(modelDef)
    

    So yeah you can wrap this in an extension method that does what you want with:

    public static MyOrmLiteExtensions {
        public static string GetTableName<T>(this IDbConnection db) {
            var modelDef = ModelDefinition<T>.Definition;
            return OrmLiteConfig.DialectProvider.GetQuotedTableName(modelDef);
        }
    }