/// <summary>
/// 將entities直接轉成DataTable
/// </summary>
/// <typeparam name="T">Entity type</typeparam>
/// <param name="entities">entity集合</param>
/// <returns>將Entity的值轉為DataTable</returns>
public DataTable EntityToDataTable<T>(IEnumerable<T> entities)
{
var result = GetEntityToDataTableSchema(typeof(T));
if (entities.Count() == 0)
{
return result;
}
var properties = typeof(T).GetProperties();
foreach (var entity in entities)
{
var dr = result.NewRow();
foreach (var property in properties)
{
dr[property.Name] = NullToDbNull(property.GetValue(entity, null));
}
result.Rows.Add(dr);
}
return result;
}
/// <summary>
/// Gets the entity to data table schema.
/// </summary>
/// <param name="entityType">Type of the entity.</param>
/// <returns>對應Entity屬性型別的DataTable</returns>
public DataTable GetEntityToDataTableSchema(Type entityType)
{
var result = new DataTable();
var properties = entityType.GetProperties();
foreach (var property in properties)
{
var columnType = property.PropertyType;
if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
//兩種寫法都可以,透過Nullable.GetUnderlyingType()比較簡潔。
//columnType = property.PropertyType.GetGenericArguments()[0];
columnType = Nullable.GetUnderlyingType(property.PropertyType);
}
var column = new DataColumn(property.Name, columnType);
result.Columns.Add(column);
}
return result;
}
///// <summary>
///// 若值為DBNull.Value, 則轉為Null
///// </summary>
///// <param name="original"></param>
///// <returns></returns>
//public object DbNullToNull(object original)
//{
// return original == DBNull.Value ? null : original;
//}
/// <summary>
/// 若值為null, 則轉成DBNull.Value
/// </summary>
/// <param name="original"></param>
/// <returns></returns>
public object NullToDbNull(object original)
{
return original ?? DBNull.Value;
}
0 意見:
張貼留言