Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get OrmLite database column name from property name

Tags:

servicestack

Let's say I have this class:

public class FooBar
{
    public long Id {get; set;}
    public string BarFoo {get; set;}
}

OrmLite when using postgresql will create table name foo_bar and columns id, and bar_foo.

I can get the table name for use in a custom query like so:

db.ExecuteSql($"INSERT INTO {db.GetTableName<SomeOtherClass>()}(bar_foo) SELECT bar_foo FROM {db.GetTableName<FooBar>()}");

If the naming convention changes or the property is re-named then the query breaks because the column bar_foo is defined as a string.

How do I define the column names in the same fashion I am defining the table names?

like image 221
Guerrilla Avatar asked Jun 28 '26 04:06

Guerrilla


1 Answers

You can get the table & column names from the dialect provider, e.g:

var dialect = db.Dialect(); //older API db.GetDialectProvider()

By their name where it will use the configured NamingStrategy:

var tableName = dialect.GetQuotedTableName(nameof(FooBar));
var columnName = dialect.GetQuotedColumnName(nameof(FooBar.BarFoo));

By OrmLite's model & field definition where it will also make use of any RDBMS [Alias] customizations defined on the model:

var modelDef = typeof(FooBar).GetModelMetadata();
var fieldDef = modelDef.GetFieldDefinition(nameof(FooBar.BarFoo));

var tableName = dialect.GetQuotedTableName(modelDef);
var columnName = dialect.GetQuotedColumnName(modelDef,fieldDef);
like image 85
mythz Avatar answered Jul 01 '26 19:07

mythz