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

I am using ServiceStack.OrmLite and want to get the total number of rows from a table. I am currently doing as instructed in the ServiceStack.OrmLite documentation via

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

      

However, the table name User

may change in the future, so I'm looking for a way not to hardcode it. Is it possible to get the table name from the corresponding class like ie

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

      

?

+3


source to share


1 answer


There are two ways to access the configuration metadata of your types:

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

      

Although in some databases you need to provide your table name, you can do it with



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

      

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

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

      

+8


source







All Articles