把List<T>变成DataTable

本文介绍了一种将List<T>转换为DataTable的方法,适用于单元测试中构造数据集而不影响实际数据库。此方法通过反射获取泛型T的所有属性,并创建相应的DataTable结构。

    最近在做一些单元测试,因为数据库里面的数据比较乱,不适合直接做单元测试的数据源,又不想自己再往里面插数据,把已经很混乱得数据库搞得更混乱,就直接写了从List<T>直接转换成对应的DataTable的类,然后在把这个DataTable再注入到单元测试里面。于是就有了这么一段代码:

ContractedBlock.gifExpandedBlockStart.gifCode
        public static DataTable ToDataTable<T>(this IEnumerable<T> list)
            
where T : class
        {
            var props 
= GetProperties<T>().ToList();
            DataTable dt 
= new DataTable();
            
foreach (var p in props)
            {
                Type t 
= p.Value.PropertyType;
                
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>))
                {
                    t 
= t.GetGenericArguments()[0];
                }
                dt.Columns.Add(p.Key, t);
            }
            
foreach (var item in list)
            {
                var row 
= dt.NewRow();
                
foreach (var p in props)
                {
                    row[p.Key] 
= p.Value.GetValue(item, null?? DBNull.Value;
                }
                dt.Rows.Add(row);
            }
            
return dt;
        }
 

    这里有一个GetProperies的方法,根据大家不同的T实体的习惯,需要对应的实现方式,因为我的实体本身是通过自定义的DbColumnAttribute来指定的,所以实现如下:

ContractedBlock.gifExpandedBlockStart.gifCode
        private static IEnumerable<KeyValuePair<string, PropertyInfo>> GetProperties<T>()
        {
            
foreach (var prop in typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public))
            {
                
if (prop.GetIndexParameters().Length > 0)
                    
continue;
                var setMethod 
= prop.GetSetMethod(false);
                
if (setMethod == null)
                    
continue;
                var attr 
= Attribute.GetCustomAttribute(prop, typeof(DbColumnAttribute), true);
                
if (attr == null)
                    
continue;
                
yield return new KeyValuePair<string, PropertyInfo>(((DbColumnAttribute)attr).ColumnName ?? prop.Name, prop);
            }

转载于:https://www.cnblogs.com/vwxyzh/archive/2009/11/11/1601186.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值