李春良

导航

Entity Framwork ToDataTable

 public static class IQueryableExtensions
    {
        public static DataTable ToDataTable(this IQueryable list)
        {
            DataTable dt = new DataTable();
            bool schemaIsBuild = false;
            PropertyInfo[] props = null;

            foreach (object item in list)
            {
                if (!schemaIsBuild)
                {
                    props = item.GetType().GetProperties();
                    foreach (var pi in props)
                    {
                        Type piType = pi.PropertyType;
                        if (piType.IsGenericType && piType.GetGenericTypeDefinition() == typeof(Nullable<>))
                        {
                            piType = piType.GetGenericArguments()[0];
                        }
                        dt.Columns.Add(new DataColumn(pi.Name, piType));
                    }

                    schemaIsBuild = true;
                }

                var row = dt.NewRow();
                foreach (var pi in props)
                {
                    row[pi.Name] = pi.GetValue(item, null) == null ? DBNull.Value : pi.GetValue(item, null);
                }

                dt.Rows.Add(row);
            }

            dt.AcceptChanges();
            return dt;
        }
    }

posted on 2012-03-29 10:30  李春良  阅读(162)  评论(0编辑  收藏  举报