logo.gif

Oak Leaf Enterprises, Inc. 

  • Home

  • Products

  • Downloads

  • About

  • Shop

  • Forum

  • Members

  • More

    Use tab to navigate through the menu items.
    0
    To see this working, head to your live site.
    • Categories
    • All Posts
    • My Posts
    Alex_SCS
    Sep 18, 2020
      ·  Edited: Sep 18, 2020

    ToDataTable method for EF

    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;
            }


    1 comment
    0
    Kevin
    Sep 18, 2020

    Thanks Alex! I think we'll make it official and add it to MM .NET with our next release.