Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataTable from FileHelpers Class -- type.GetProperties() returns empty array

I've successfully pulled a CSV file into the following class:

[DelimitedRecord(",")]
[IgnoreFirst(1)] // ignores first line of file, since it's a header
public class Employee {
    public string EmployeeId;
    public string FirstName;
    public string LastName;
    // etc.
}

I need to create a DataTable based on that class in order to use SqlBulkCopy. I've found several examples, but the following method doesn't work for me:

private static DataTable createEmptyDataTable(Type myType) {
        DataTable dt = new DataTable();

        foreach (PropertyInfo info in myType.GetProperties()) {
            dt.Columns.Add(new DataColumn(info.Name, info.PropertyType));
        }

        return dt;
    }

The problem is with myType.GetProperties(). It's not throwing an error, but it returns nothing. The PropertyInfo array that it should return is empty. Been at this a while and can't figure out the problem...

EDIT: I've also used this variant with no success:

private static DataTable createEmptyDataTable(Type myType) {
        DataTable dt = new DataTable();
        PropertyInfo[] infoArray = myType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);

        foreach (PropertyInfo info in infoArray) {
            dt.Columns.Add(new DataColumn(info.Name, info.PropertyType));
        }

        return dt;
    }
like image 655
Nate Avatar asked Nov 29 '22 15:11

Nate


2 Answers

Your Employee class contains fields, not properties. Use rather

myType.GetFields()
like image 65
Dominic Avatar answered Dec 18 '22 21:12

Dominic


When working with Properties : You need to specify the scope for the Get Properties, try this to return all property types : GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);

When working with fields (i.e. no get/set), its similar, just a different function. See : http://msdn.microsoft.com/en-us/library/ch9714z3.aspx

like image 28
David C Avatar answered Dec 18 '22 23:12

David C