Beispiel #1
0
        private void GetExtraColumns <TId, TUId>(IDynamicRepository repository, List <LookupObject <TId, TUId> > lookupCollection, List <DbColumn> columns, string lookupName, bool includeDeleted, List <FilterSearchCriteria> filters = null) where TId : IEquatable <TId>
            where TUId : struct
        {
            // Get Lookup object properties
            var properties = typeof(LookupObject <TId, TUId>).GetProperties();

            StringBuilder extraQuery = new StringBuilder();

            // Get extra Columns
            List <DbColumn> extraColumns = columns.Where(col => !properties.Any(prop => prop.Name == col.Name)).ToList();

            // If there are extra columns
            if (extraColumns != null && extraColumns.Count > 0)
            {
                // Join all columns name seprated by ,
                string columnStr = string.Join(",", extraColumns.Select(col => col.Name));

                extraQuery.Append($"SELECT Id, {columnStr} FROM dbo.LK_{lookupName} AS E");

                // Apply filter on extra query
                ApplyFilters <TUId>(extraQuery, includeDeleted, columns.Any(col => col.Name.ToLower() == LookUpConsts.CreatedByField.ToLower()), filters, columns);

                // Build dynmic type
                TypeBuilder builder = DynmicTypeBuilder.CreateTypeBuilder("MyDynmicAssembly", "MyModule", "MyType");

                // Find Id Column
                DbColumn idColumn = columns.First(x => x.Name.ToLower() == LookUpConsts.IdField.ToLower());

                // If id not exist
                if (idColumn == null)
                {
                    throw new Exception("Can not find Id column for lookup entity.");
                }

                // Add id property.
                DynmicTypeBuilder.CreateAutoImplementedProperty(builder, idColumn.Name, idColumn.ColumnType);

                // Add columns as propreties at dynmic type.
                extraColumns.ForEach(col => DynmicTypeBuilder.CreateAutoImplementedProperty(builder, col.Name, col.ColumnType));

                // Create Type of builder.
                Type resultType = builder.CreateType();

                List <dynamic> extraFields = repository.ExecuteQuery(resultType, extraQuery.ToString());

                foreach (var item in lookupCollection)
                {
                    var dynmicObject = extraFields.FirstOrDefault(x => item.Id == x.Id);

                    item.ExtraFields = new Dictionary <string, object>();

                    extraColumns.ForEach(col =>
                    {
                        item.ExtraFields.Add(col.Name, resultType.GetProperty(col.Name).GetValue(dynmicObject));
                    });
                }
            }
        }