From a previous thread I asked how to get a registry from an id in a generic way, the answer I got was this:
public class DBAccess
{
public virtual DataBaseTable GetById<DataBaseTable>(int id, Table<DataBaseTable> table) where DataBaseTable : class
{
var itemParameter = Expression.Parameter(typeof(DataBaseTable), "item");
var whereExpression = Expression.Lambda<Func<DataBaseTable, bool>>
(
Expression.Equal(
Expression.Property(
itemParameter,
"Id"
),
Expression.Constant(id)
),
new[] { itemParameter }
);
return table.Where(whereExpression).Single();
}
}
Which works nice, but now I’m stuck not knowing how to get any of its attributes, to give a concrete question, how could I make this below function work?
public static int GetRelatedTableId<DataBaseTable>
(Table<DataBaseTable> table,String RelatedTableId) where DataBaseTable : class
{
DBAccess RegistryGet = new DBAccess();
DataBaseTable tab = RegistryGet.GetById<DataBaseTable>(id, table);
return tab.getAttributeByString(RelatedTableId);//i just made this up
}
Update Solution
Thanks to the link below i managed to solve this
public static int GetRelatedTableId<DataBaseTable>
(Table<DataBaseTable> table,String RelatedTableId) where DataBaseTable : class
{
DBAccess RegistryGet = new DBAccess();
DataBaseTable tab = RegistryGet.GetById<DataBaseTable>(id, table);
return (int)(tab.GetType().GetProperty(RelatedTableId)).GetValue(tab, null);
}
If your property name is only known at runtime, then you can use reflection to inspect the type
DataBaseTable, find the property of interest by name, and then retrieve its value from your instancetab.See the answer to this question for an example: How can I get the value of a string property via Reflection?
Clarification: Yes, your type is a generic argument, but
typeof(DataBaseTable)ortab.GetType()will still allow you to inspect the particular type being used.