Object To DataView或DataSet或DataTable并返回对象

时间:2009-12-14 22:29:26

标签: c# ado.net extension-methods dataset

我们有一个带有遗留模块的mish-mash应用程序仍然使用DataSet,DataViews和DataTables但是我们有大多数数据库ORMed,除了这个模块的数据库。我想知道是否有人可以指点如何建立像

这样的扩展
/* 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>(); 

我不知道什么时候我们会有时间在应用程序的其他层上工作并从DataSet中释放它。我可能听起来很疯狂,但这只是一个想法。当我需要支持/修复该应用程序时,我会做噩梦。

2 个答案:

答案 0 :(得分:1)

您可以使用反射,例如:

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;
    }
}

答案 1 :(得分:0)

您可以使用它来从数据表中获取对象

 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>();