Forum Posts

Alex_SCS
Sep 18, 2020
In Entity Framework
Greetings from Silver Creek Software! We are currently implementing Mere Mortals in our project, and I thought we could kick things off in this new forum by sharing a customization/enhancement we've made to the base Business Object (sometimes referred to as "ABusinessObject") class definition to generate a DataTable from a list of entities: /// <summary> /// Converts a collection of <see cref="EntityType"/> objects to a <see cref="DataTable"/> for easier user-consumption /// </summary> /// <param name="pEntityList">(Optional) Target collection, uses <see cref="EntityList"/> if unspecified</param> /// <returns>New <see cref="DataTable"/> with data from entities</returns> public DataTable ToDataTable(IEnumerable<EntityType> pEntityList = null) { DataTable dataTable = new DataTable(); IEnumerable<EntityType> entityList = pEntityList != null ? pEntityList : EntityList; // Create the columns by reflecting the entity type's properties // (TO-DO: Take advantage of the "DisplayName" data annotation (or Culture-sensitive resource file) as an alternative to using the property name) typeof(EntityType).GetProperties().ToList() .ForEach(x => dataTable.Columns.Add(x.Name, Nullable.GetUnderlyingType(x.PropertyType) ?? x.PropertyType)); // Generate rows foreach (EntityType entity in entityList) { DataRow newRow = dataTable.NewRow(); typeof(EntityType).GetProperties().ToList() .ForEach(x => newRow[x.Name] = x.GetValue(entity) ?? DBNull.Value); dataTable.Rows.Add(newRow); } return dataTable; }
0
1
63
Alex_SCS
More actions