简体   繁体   English

在ServiceStack.OrmLite中获取运行时的类的表名/避免硬编码表名

[英]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. 我使用ServiceStack.OrmLite并希望从表中获取行的总数。 I currently do as pointed out in the ServiceStack.OrmLite documentation via 我目前正在ServiceStack.OrmLite文档中指出

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. 但是,该表的名称User可能在将来发生变化,因此我正在寻找一种不对其进行硬编码的方法。 Is it possible to get the table's name from its according class, like ie 是否有可能从其类中获取表的名称,例如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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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