안녕하세요 다음과 같이 DataTable을 특정 모델 클래스의 List<T>타입으로 Convert해서 사용하고 있습니다.
그런데 성능상 데이터가 많은 편이 아닌데도 느린 부분이 있어 혹시 어디 부분에서 성능이 떨어지는지 도움 요청드립니다.
소스는 다음과 같고, 모델 클래스의 각각 Property에 DataTable의 해더명을 어트리뷰트로 정의해서 자동으로 Property의 타입에 맞게 캐스팅해서 속성을 채우는 방식입니다.
테스트시 DataTable에 약 50개 정도의 Row를 List<T>형식으로 변환 했을때 1s ~ 2s사이 정도 시간이 지연 됬습니다.
소스에 문제가 되는 부분이 있는지 도움 요청 드립니다.
public static List<T> DataTableToList<T>(DataTable table) where T : class, new()
{
if (table == null) return null;
try
{
List<T> list = new List<T>();
foreach (DataRow row in table.AsEnumerable())
{
T obj = new T();
foreach (PropertyInfo prop in obj.GetType().GetProperties())
{
try
{
string headerCaption = null;
// 모델 클래스(T) 속성에 설정되어 있는 어트리뷰트 Get
object[] atts = prop.GetCustomAttributes(typeof(ExtensionEnumAttribute), false);
if (atts != null && atts.Length <= 0)
{
continue;
}
ExtensionEnumAttribute att = (ExtensionEnumAttribute)atts[0];
if (att == null || att.Objs == null || att.Objs.Length < 0 || string.IsNullOrWhiteSpace(att.Objs[0].ToString()))
{
headerCaption = prop.Name;
}
else
{
// 속성에 설정되어 있는 컬럼 헤더 타이틀 어리트뷰트 값
headerCaption = att.Objs[0].ToString();
}
PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);
if (propertyInfo.PropertyType.IsEnum)
{
object enumVal = Enum.Parse(propertyInfo.PropertyType, row[headerCaption].ToString());
propertyInfo.SetValue(obj, enumVal, null);
}
else
{
Type t = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType;
if (row[headerCaption] != DBNull.Value)
{
propertyInfo.SetValue(obj, Convert.ChangeType(row[headerCaption], t), null);
}
else
{
propertyInfo.SetValue(obj, null, null);
}
}
}
catch(Exception ex)
{
// 데이터 테이블에 없는 모델 클래스(T) 속성
// 예] IsSelectCheck 속성 등..
continue;
}
}
list.Add(obj);
}
return list;
}
catch(Exception ex)
{
throw new Exception("데이터 테이블 -> 모델 변환 오류");
}
}
[최초 등록일: ]
[최종 수정일: 5/26/2017]