ConvertToTable(from Poco class to Table)

来源:互联网 发布:ubuntu服务器密码修改 编辑:程序博客网 时间:2024/06/17 07:31
 protected DataTable ConvertToDataTable(IList<T> list)
        {
            DataTable table = new DataTable();
            int indexOfGeoColumn = -1;
            List<DataColumn> primaryKeys = new List<DataColumn>();


            for (int i = 0; i < _columns.Count(); i++)
            {
                var col = _columns[i];
                Type propType = col.PropertyType;




                DataColumn column = new DataColumn();
                column.ColumnName = col.Name;


                if (propType.IsGenericType && propType.GetGenericTypeDefinition() == typeof(Nullable<>))
                    column.DataType = Nullable.GetUnderlyingType(propType);
                else
                    column.DataType = propType;


                RequiredAttribute required = (RequiredAttribute)Attribute.GetCustomAttribute(propType, typeof(RequiredAttribute));
                if (required != null)
                    column.AllowDBNull = false;


                //special case that we need to consider
                if (propType.Equals(typeof(DbGeography)))
                {
                    column.DataType = typeof(SqlGeography);
                    indexOfGeoColumn = i;
                }


                if (_keyNames.Contains(col.Name))
                    primaryKeys.Add(column);


                table.Columns.Add(column);
            }


            table.PrimaryKey = primaryKeys.ToArray();


            object[] values = new object[_columns.Length];
            for (int j = 0; j < list.Count; j++)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    if (indexOfGeoColumn == i)
                    {
                        var dbGeo = (DbGeography)_columns[i].GetValue(list[j]);
                        if (dbGeo == null)
                        {
                            values[i] = null;
                        }
                        else
                        {
                            SqlGeography sqlGeo2 = SqlGeography.STGeomFromWKB(new SqlBytes(dbGeo.AsBinary()), dbGeo.CoordinateSystemId);
                            values[i] = sqlGeo2;
                        }
                    }
                    else
                    {
                        values[i] = _columns[i].GetValue(list[j]);
                    }
                }
                table.Rows.Add(values);
            }
            return table;
        } 
0 0