public object GetById(string typeName, string id)
{
var ar = typeName.Split(',');
var currentType = Type.GetType(ar[0] + ", " + ar[1]);
var tableName = ((TableNameAttribute)Attribute.GetCustomAttribute(currentType, typeof(TableNameAttribute))).Value;
var primaryKeyColum = "id";
var primKeyAttri = currentType.GetCustomAttributes().Where(x => x.GetType() == typeof(PrimaryKeyAttribute));
if (primKeyAttri.Any())
primaryKeyColum = ((PrimaryKeyAttribute)primKeyAttri.First()).Value;
foreach (var property in currentType.GetProperties())
{
var keyAttri = property.GetCustomAttributes().Where(x => x.GetType() == typeof (PrimaryKeyColumnAttribute));
if (keyAttri.Any())
primaryKeyColum = property.Name;
}
var uioMaticAttri = (UIOMaticAttribute)Attribute.GetCustomAttribute(currentType, typeof(UIOMaticAttribute));
var db = (Database)DatabaseContext.Database;
if (!string.IsNullOrEmpty(uioMaticAttri.ConnectionStringName))
db = new Database(uioMaticAttri.ConnectionStringName);
var dyn = db.Query<dynamic>(Sql.Builder
.Append("SELECT * FROM [" + tableName +"]")
.Append("WHERE ["+primaryKeyColum+"] =@0", id));
var props = currentType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(x => x.GetSetMethod() != null);
// create an instance of the type
var obj = Activator.CreateInstance(currentType);
// set property values using reflection
var values = (IDictionary<string, object>)dyn.FirstOrDefault();
foreach (var prop in props)
{
var columnAttri =
prop.GetCustomAttributes().Where(x => x.GetType() == typeof(ColumnAttribute));
var propName = prop.Name;
if (columnAttri.Any())
propName = ((ColumnAttribute)columnAttri.FirstOrDefault()).Name;
if(values.ContainsKey(propName))
prop.SetValue(obj, values[propName]);
}
return obj;
}