Reputation: 1453
suppose I have my data class
[TableName("some_table")]
public class MyData
{
[ColumnName("some_column")
public string Name {get;set;}
}
Now I want to execute a plain SQL query against my table, but I don't want to hardcode table/column name in my query. E.g. "update some_table set some_column = replace(some_column, '...', '...')" is bad because table, column name are hardcoded into the request. I would prefer something like "update {{ MyData }} set {{ Name }} = ...", where {{ MyData }} {{ Name }} would be replaced by table, column name from NPoco database mapping. Is it possible to retrieve this info from NPoco database?
Upvotes: 2
Views: 1159
Reputation: 1453
I finally came up with these extension methods that retrieve table name from type and column name for property:
public static class NPOCOExtensions
{
public static string GetTableNameFromType<T>(this Database db)
{
return db.PocoDataFactory.TableInfoForType(typeof(T)).TableName;
}
public static string GetColumnNameFromProperty<T>(this Database db, Expression<Func<T, object>> selector)
{
var memberName = ((MemberExpression)selector.Body).Member.Name;
var columnName = db.PocoDataFactory.ForType(typeof(T)).Members.Where(x => x.Name == memberName).First().PocoColumn.ColumnName;
return columnName;
}
}
Upvotes: 2