Объект в DataView, DataSet или DataTable и обратно в объект

У нас есть приложение mish-mash с устаревшим модулем, которое по-прежнему использует DataSets, DataViews и DataTables, однако у нас есть большинство баз данных ORMed, кроме DB для этого модуля. Мне было интересно, может ли кто-нибудь подсказать мне, как создавать такие расширения, как

/* generates a dataset called CustomerDS with 
DataTable called Customer uses property names as DataColumn name */
var dataset =_customer.AsDataSet(); 
/* Converts the dataset to required object or 
throws exception if its cant convert*/
 var customerEntity = _dataset.ToObject<Customer>(); 

Я не знаю, когда у нас будет время поработать над другими уровнями приложения и освободить его от DataSets. Я могу показаться сумасшедшим, но это всего лишь мысль. Мне снятся кошмары, когда мне нужно поддержать / исправить это приложение.


person Perpetualcoder    schedule 14.12.2009    source источник
comment
Из отдельных таблиц, возможно, что-то вроде: stackoverflow.com/questions/564366/ общий-список-в-данные   -  person Marc Gravell    schedule 15.12.2009
comment
И в другом направлении: stackoverflow.com/ questions / 545328 /   -  person Marc Gravell    schedule 15.12.2009


Ответы (2)


Вы можете использовать отражение, например:

class Program {
        public static void Start( string[] args ) {
            var john = new Customer {
                CustomerID = Guid.NewGuid(),
                CustomerName = "John",
                CustomerCode = "J-O"
            };

            var tblJohn = john.ToDataTable();
            var clonedJohn = tblJohn.Rows[0].ToDataObject<Customer>();
        }
}

[AttributeUsage(AttributeTargets.Property)]
public class DataColumnAttribute : Attribute { }
public class Customer {
    [DataColumn]
    public Guid CustomerID { get; set; }

    [DataColumn]
    public string CustomerName { get; set; }

    [DataColumn]
    public string CustomerCode { get; set; }
}

public static class DataObjectExtensions {
    public static T ToDataObject<T>( this DataRow dataRow ) where T : new() {
        var dataObject = Activator.CreateInstance<T>();
        var tpDataObject = dataObject.GetType();

        foreach ( var property in tpDataObject.GetProperties() ) {
            var attributes = property.GetCustomAttributes( typeof( DataColumnAttribute ), true );
            if ( null != attributes && attributes.Length > 0 ) {
                if ( property.CanWrite ) {
                    DataColumn clm = dataRow.Table.Columns[property.Name];
                    if ( null != clm ) {
                        object value = dataRow[clm];
                        property.SetValue( dataObject, value, null );
                    }
                }
            }
        }

        return dataObject;
    }
    public static DataTable ToDataTable( this object dataObject ) {
        var tpDataObject = dataObject.GetType();

        DataTable tbl = new DataTable();
        DataRow dataRow = tbl.NewRow();
        foreach ( var property in tpDataObject.GetProperties() ) {
            var attributes = property.GetCustomAttributes( typeof( DataColumnAttribute ), true );
            if ( null != attributes && attributes.Length> 0 ) {
                if ( property.CanRead ) {
                    object value = property.GetValue( dataObject, null );
                    DataColumn clm = tbl.Columns.Add( property.Name, property.PropertyType );
                    dataRow[clm] = value;
                }
            }
        }

        tbl.Rows.Add( dataRow );
        tbl.AcceptChanges();
        return tbl;
    }
}
person TcKs    schedule 14.12.2009

Вы можете использовать это, чтобы получить объект из таблицы данных

 public static class Extensions
    {
        public static List<T> ToList<T>(this DataTable table) where T : new()
        {
            IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
            List<T> result = new List<T>();

            foreach (var row in table.Rows)
            {
                var item = CreateItemFromRow<T>((DataRow)row, properties);
                result.Add(item);
            }

            return result;
        }

        private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new()
        {
            T item = new T();
            foreach (var property in properties)
            {
                if (property.PropertyType == typeof(System.DayOfWeek))
                {
                    DayOfWeek day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), row[property.Name].ToString());
                    property.SetValue(item,day,null);
                }
                else
                {
                    property.SetValue(item, row[property.Name], null);
                }
            }
            return item;
        }
    }

и используйте это так

List<Employee> lst = ds.Tables[0].ToList<Employee>();
person d.popov    schedule 14.08.2013