简体   繁体   中英

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 ie

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

?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM