I'm trying to make a generic class to save log
Here we use entity framework so imagine we have table mng_users(string usr_name, int usr_id) creating the respective class for itentity)
is there a way to implement the toDataTable method converting the entity into a datatable(not a list, having 1 row only) so i can do something like this:
having mng_users1 and mng_users2 as mng_users entity class(both with the same id but diff name)
call method "savelog(mng_users1, mng_users2);" and do the following code:
private DataTable toDataTable(Object T)
{
DataTable vDataTable = new DataTable();
//AddColums here
//AddRow with the respective values here
return vDataTable;
}
public void savelog(Object newObject, Object oldObject)
{
DataTable newvalue, oldvalue;
newvalue = toDataTable(newObject);
oldvalue = toDataTable(oldObject);
string FieldNames = string.Empty, FieldValuesFrom = string.Empty, FieldValuesTo = string.Empty;
foreach (DataColumn item in newvalue.Columns)
{
if (newvalue.Rows[0][item].ToString() != oldvalue.Rows[0][item].ToString())
{
FieldNames += (FieldNames.Length > 0 ? " | " : string.Empty) + item.ColumnName;
FieldValuesFrom += (FieldValuesFrom.Length > 0 ? " | " : string.Empty) + newvalue.Rows[0][item].ToString();
FieldValuesTo += (FieldValuesTo.Length > 0 ? " | " : string.Empty) + oldvalue.Rows[0][item].ToString();
}
}
// Save log to sql code here
}
My improvement to the above sample:
added support for Nullable property types
public static DataTable ToDataTable<T>(this IEnumerable<T> entityList) where T : class
{
var properties = typeof(T).GetProperties();
var table = new DataTable();
foreach (var property in properties)
{
var type = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
table.Columns.Add(property.Name, type);
}
foreach (var entity in entityList)
{
table.Rows.Add(properties.Select(p => p.GetValue(entity, null)).ToArray());
}
return table;
}
Something like the below code should work. It may need to be tweaked depending on whether properties are private
/protected
and if any of the public properties are indexed, but it should get you started.
private DataTable ToDataTable<T>(T entity) where T : class
{
var properties = typeof(T).GetProperties();
var table = new DataTable();
foreach(var property in properties)
{
table.Columns.Add(property.Name, property.PropertyType);
}
table.Rows.Add(properties.Select(p => p.GetValue(entity, null)).ToArray());
return table;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With