For coonverting Linq to DataTable I am using the following Extension Method(Taken from Stackoverflow)
Linq to DataTable
public static DataTable ToDataTable<T>(this IEnumerable<T> items)
{
DataTable table = new DataTable(typeof(T).Name);
PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public |
BindingFlags.Instance);
foreach (var prop in props)
{
Type propType = prop.PropertyType;
// Is it a nullable type? Get the underlying type
if (propType.IsGenericType &&
propType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
propType = new NullableConverter(propType).UnderlyingType;
table.Columns.Add(prop.Name, propType);
}
foreach (var item in items)
{
var values = new object[props.Length];
for (var i = 0; i < props.Length; i++)
values[i] = props[i].GetValue(item, null);
table.Rows.Add(values);
}
return table;
}
WriteXml
PersonDB.PersonDataContext con = new PersonDB.PersonDataContext();
DataTable tb = new DataTable();
tb = con.Persons.ToDataTable();
tb.WriteXml(@"d:\temp\Person.xml");
Question
The Extension Method creates XML file.But for null values no element is created in XML file.Say if Commission field is null then commission element is missing in Xml generation. I want to insert element with empty string for null values (ref type) and (0.00) for decimals and (0) for integers. where do i need to make change?