mardi 26 juillet 2016

Generic List To DataTable

I wrote something maybe someone can learn from:

public DataTable BulkUploadToSqlServer<T>(List<T> ListToInsert, string DataTableName)
    {
        Type typeParameterType = typeof(T);
        var attributes = typeParameterType.GetProperties();

        var dt = new DataTable(DataTableName);

        for (int attribute = 0; attribute < attributes.Length; ++attribute)
            dt.Columns.Add(attributes[attribute].Name, attributes[attribute].PropertyType);


        for (int obj = 0; obj < ListToInsert.Count; ++obj)
        {
            DataRow dr = dt.NewRow();
            for (int attribute = 0; attribute < attributes.Length; ++attribute)
                dr[attributes[attribute].Name] = ListToInsert[obj].GetType().GetProperty(attributes[attribute].Name).GetValue(ListToInsert[obj], null);
            dt.Rows.Add(dr);
        }
        return dt;
    }

we can always use FastMember and just write:

DataTable table = new DataTable();
        using (var reader = ObjectReader.Create(ListToInsert))
        {
            table.Load(reader);
        }

I'm writing this to all of you that want to have some more experience in reflection in windows environment.

you can always use FastMember solution, I don't know how much you'll be able to learn from it.

good luck.





Aucun commentaire:

Enregistrer un commentaire