Dumping a Database with Reflection

I needed a function recently to dump data from database tables to a tab-delimited file, for reporting purposes.

The irony of this was that rather than wanting nicely typed objects and properties, what I wanted was something that would just take some rows and dump the data out. So although my EntityFramework-based project had all of the data appropriately typed, I wanted to get all of the Entity Properties that had been defined in the original database schema, iterate through them.

Clearly Reflection is the solution here, with one caveat: the only properties that I wanted were the properties of the generated class and not those that pertained to the Entity Framework itself. So, how to identify the properties that belong to my table-derived classes?

The answer is that the “Module” property of the PropertyInfo structure will contain the Module that the property in question is defined in, and any properties supplied as part of the Entity Framework will be identified as being define in System.Data.Entity.dll.

So, in the code below I compare the Module data of the PropertyInfo with the Module property of the context from which the Entities come, and only output them if they are the same.


private MyEntities db = new MyEntities();

var referAFriendData = db.ReferFriends.ToList();
if(referAFriendData.Count > 0)
{
    var properties = referAFriendData
                          .FirstOrDefault().GetType().GetProperties();
    var headerNames = (from prop in properties
                            where
                            String.Equals(prop.Module.Name,
                            db.GetType().Module.Name, 
                            StringComparison.OrdinalIgnoreCase)
                            
                            select prop.Name).ToList();

    const string attachment = "attachment; filename=referAFriend.xls";
    Response.ClearContent();
    Response.AddHeader("content-disposition", attachment);
    Response.ContentType = "application/vnd.ms-excel";
    string tab = "";
    foreach (var headerName in headerNames)
    {
        Response.Write(tab + headerName);
         tab = "t";
     }

    Response.Write("n");

    foreach (var row in referAFriendData)
    {
        tab = row.GetType().GetProperties()

       .Where(prop => string.Equals(
		    prop.Module.Name,
		    db.GetType().Module.Name,
	StringComparison.OrdinalIgnoreCase))

	.Select(property => property.GetValue(row, null))

	.Aggregate(tab, (current, d) =>
	current + String.Format("{0}t", (object[]) d));

        Response.Write(tab + "n");
    }
    Response.End();
}