Inflate DataTable To Data Entity (Generic class)
DataToEntity is usefull for Dot Net 2.0 where developer can convert ADO.NET's DataTable convert into object without extra coding.
DataToEntity is usefull for Dot Net 2.0 where developer can convert ADO.NET's DataTable convert into object without extra coding.
using
System;
using
System.Collections.Generic;
using
System.Data;
using
System.Reflection;
namespace
Dotnet2Test
{
public static class DataToEntity
{
#region inflate
///
/// Inflate data from dataset tot entity
///
public static TEntityCollection
Inflate<TEntityCollection, TEntity>(DataSet
ds)
where
TEntityCollection : List<TEntity>, new()
where
TEntity : new()
{
TEntityCollection entityCollection
= new TEntityCollection();
DataTable
dt = null;
if
(ds.Tables.Count > 0)
{
if
(ds.Tables.Count == 1)
dt = ds.Tables[0];
else
dt = ds.Tables[typeof (TEntity).Name];
}
else
throw
new Exception("invalid Dataset");
return
Inflate<TEntityCollection>(dt);
}
public static TEntityCollection
Inflate<TEntityCollection, TEntity>(DataTable
dt)
where
TEntityCollection : List<TEntity>, new()
where
TEntity : new()
{
TEntityCollection entityCollection
= new TEntityCollection();
if
(dt != null)
{
foreach
(DataRow dr in
dt.Rows)
{
TEntity tmpEntity =
Inflate<TEntity>(dr);
entityCollection.Add(tmpEntity);
}
}
else
throw
new Exception("No data found");
return
entityCollection;
}
///
/// Inflate data from dataset tot entity
///
///
public static TEntity Inflate<TEntity>(DataSet ds)
where
TEntity : new()
{
DataTable
dt = null;
if
(ds.Tables.Count > 0)
{
if
(ds.Tables.Count == 1)
dt = ds.Tables[0];
else
dt = ds.Tables[typeof (TEntity).Name];
}
else
throw new
Exception("invalid
Dataset");
return
Inflate<TEntity>(dt);
}
public static TEntity Inflate<TEntity>(DataTable dt)
where
TEntity : new()
{
TEntity tmpEntity = new TEntity();
if
(dt != null)
{
if
(dt.Rows.Count > 0)
tmpEntity =
Inflate<TEntity>(dt.Rows[0]);
else
throw
new Exception("No data found");
}
else
throw
new Exception("No data found");
return
tmpEntity;
}
public static TEntity Inflate<TEntity>(DataRow dr)
where
TEntity : new()
{
TEntity tmpEntity = new TEntity();
Inflate(dr, tmpEntity);
return
tmpEntity;
}
public static void Inflate(DataRow dr, object
tmpEntity)
{
if
(dr != null && tmpEntity != null)
{
foreach
(DataColumn dc in
dr.Table.Columns)
{
PropertyInfo
metadata = tmpEntity.GetType().GetProperty(dc.ColumnName);
if
(metadata != null)
{
metadata.SetValue(tmpEntity,
dr[dc], null);
}
}
}
else
throw
new Exception("No data found or entity is null");
}
#endregion
}
}