Esempio n. 1
0
        protected override async Task <IEnumerable <SelectListItem> > GetSelectListItemsAsync(SelectListContext context)
        {
            //Get DbContext from DI container
            DbContext db = (DbContext)context.HttpContext.RequestServices.GetService(DbContextType);

            if (db == null)
            {
                throw new Exception("Database not found");
            }

            //Get DbSet as IQueryable
            IQueryable query = (IQueryable)_dbContextSetMethod.MakeGenericMethod(ModelType).Invoke(db, null);

            if (!string.IsNullOrEmpty(RawSql))
            {
                query = (IQueryable)RelationalQueryableExtensions.FromSql((dynamic)query, RawSql, RawSqlParameters);
            }

            if (!EnableChangeTracking)
            {
                query = (IQueryable)EntityFrameworkQueryableExtensions.AsNoTracking((dynamic)query);
            }

            if (context.SelectedOnly)
            {
                //Select by Id
                var whereClause = DbContextHelper.SearchForEntityByValues(ModelType, DataValueField, context.CurrentValues);
                query = (IQueryable)_dbContextWhereClauseMethod.MakeGenericMethod(ModelType).Invoke(null, new object[] { query, whereClause });
            }
            else
            {
                if (context.ModelExplorer.Metadata is DefaultModelMetadata defaultModelMetadata)
                {
                    //Loop over where clauses

                    IEnumerable <SelectListDbWhereEqualsAttribute> whereClauseAttributes = null;
                    if (defaultModelMetadata.MetadataKind == ModelMetadataKind.Property)
                    {
                        whereClauseAttributes = defaultModelMetadata.Attributes.PropertyAttributes.OfType <SelectListDbWhereEqualsAttribute>().Where(a => a.SelectListId == this.SelectListId);
                    }
                    else if (defaultModelMetadata.MetadataKind == ModelMetadataKind.Type)
                    {
                        whereClauseAttributes = defaultModelMetadata.Attributes.TypeAttributes.OfType <SelectListDbWhereEqualsAttribute>().Where(a => a.SelectListId == this.SelectListId);
                    }

                    if (whereClauseAttributes != null)
                    {
                        foreach (var where in whereClauseAttributes)
                        {
                            var whereClause = LamdaHelper.SearchForEntityByProperty(ModelType, where.PropertyName, where.Values);
                            query = (IQueryable)_dbContextWhereClauseMethod.MakeGenericMethod(ModelType).Invoke(null, new object[] { query, whereClause });
                        }
                    }
                }
            }

            //Order By
            if (!string.IsNullOrWhiteSpace(OrderByProperty))
            {
                if (OrderByType == "asc")
                {
                    query = (IQueryable)_dbContextOrderByMethod.MakeGenericMethod(ModelType).Invoke(null, new object[] { query, OrderByProperty, true });
                }
                else
                {
                    query = (IQueryable)_dbContextOrderByMethod.MakeGenericMethod(ModelType).Invoke(null, new object[] { query, OrderByProperty, false });
                }
            }

            //Skip
            query = (IQueryable)Queryable.Skip((dynamic)query, Skip);

            //Take
            query = (IQueryable)Queryable.Take((dynamic)query, Take);

            //Get Results
            IEnumerable results = (IEnumerable)(await EntityFrameworkQueryableExtensions.ToListAsync((dynamic)query, CancellationToken.None));

            return(new ModelMultiSelectList(context.Html, results, DataValueField, DataTextFieldExpression));
        }
        public static IList <SelectListItem> GetSelectListFromDatabase <TDbContext>(this IHtmlHelper <dynamic> htmlHelper, string propertyName, bool selectedOnly = false) where TDbContext : DbContext
        {
            var modelExplorer = ExpressionMetadataProvider.FromStringExpression(propertyName, htmlHelper.ViewData, htmlHelper.MetadataProvider);

            Microsoft.AspNetCore.Mvc.ModelBinding.ModelMetadata metadata = modelExplorer.Metadata;

            var dropdownModelType = ((Type)metadata.AdditionalValues["DropdownModelType"]);
            var keyProperty       = ((string)metadata.AdditionalValues["KeyProperty"]);
            var valueProperty     = ((string)metadata.AdditionalValues["DisplayExpression"]);
            var bindingProperty   = ((string)metadata.AdditionalValues["BindingProperty"]);

            var orderByProperty = ((string)metadata.AdditionalValues["OrderByProperty"]);
            var orderByType     = ((string)metadata.AdditionalValues["OrderByType"]);

            var physicalFilePath = ((string)metadata.AdditionalValues["PhysicalFilePath"]);
            var fileFolderId     = ((string)metadata.AdditionalValues["FileFolderId"]);

            if (!string.IsNullOrEmpty(fileFolderId))
            {
                physicalFilePath = Server.GetWwwFolderPhysicalPathById(fileFolderId);
            }
            var physicalFolderPath = ((string)metadata.AdditionalValues["PhysicalFolderPath"]);
            var folderFolderId     = ((string)metadata.AdditionalValues["FolderFolderId"]);

            if (!string.IsNullOrEmpty(folderFolderId))
            {
                physicalFolderPath = Server.GetWwwFolderPhysicalPathById(folderFolderId);
            }

            var nullable = ((bool)metadata.AdditionalValues["Nullable"]);

            var options = ((IEnumerable <string>)metadata.AdditionalValues["Options"]);

            Type propertyType           = GetNonNullableModelType(metadata);
            List <SelectListItem> items = new List <SelectListItem>();
            List <string>         ids   = new List <string>();

            if (propertyType != typeof(string) && (propertyType.GetInterfaces().Contains(typeof(IEnumerable))))
            {
                if (modelExplorer.Model != null)
                {
                    foreach (var val in (IEnumerable)modelExplorer.Model)
                    {
                        if (val != null)
                        {
                            if (!string.IsNullOrWhiteSpace(bindingProperty))
                            {
                                ids.Add(val.GetPropValue(bindingProperty).ToString());
                            }
                            else
                            {
                                ids.Add(val.ToString());
                            }
                        }
                    }
                }
            }
            else
            {
                if (modelExplorer.Model != null)
                {
                    if (!string.IsNullOrWhiteSpace(bindingProperty))
                    {
                        ids.Add(modelExplorer.Model.GetPropValue(bindingProperty).ToString());
                    }
                    else
                    {
                        ids.Add(modelExplorer.Model.ToString());
                    }
                }
            }

            if (!string.IsNullOrEmpty(physicalFolderPath))
            {
                var repository = htmlHelper.FileSystemGenericRepositoryFactory().CreateFolderRepositoryReadOnly(default(CancellationToken), physicalFolderPath, true);
                var data       = repository.GetAll(LamdaHelper.GetOrderByFunc <DirectoryInfo>(orderByProperty, orderByType), null, null);
                keyProperty = nameof(DirectoryInfo.FullName);

                data.ToList().ForEach(item =>

                                      items.Add(new SelectListItem()
                {
                    Text     = GetDisplayString(htmlHelper, item, valueProperty).Replace(physicalFolderPath, ""),
                    Value    = item.GetPropValue(nameof(DirectoryInfo.FullName)) != null ? item.GetPropValue(nameof(DirectoryInfo.FullName)).ToString().Replace(physicalFolderPath, "") : "",
                    Selected = item.GetPropValue(keyProperty) != null && ids.Contains(item.GetPropValue(keyProperty).ToString().Replace(physicalFolderPath, ""))
                }));
            }
            else if (!string.IsNullOrEmpty(physicalFilePath))
            {
                var repository = htmlHelper.FileSystemGenericRepositoryFactory().CreateFileRepositoryReadOnly(default(CancellationToken), physicalFilePath, true);
                var data       = repository.GetAll(LamdaHelper.GetOrderByFunc <FileInfo>(orderByProperty, orderByType), null, null);
                keyProperty = nameof(FileInfo.FullName);

                data.ToList().ForEach(item =>

                                      items.Add(new SelectListItem()
                {
                    Text     = GetDisplayString(htmlHelper, item, valueProperty),
                    Value    = item.GetPropValue(keyProperty) != null ? item.GetPropValue(keyProperty).ToString().Replace(physicalFilePath, "") : "",
                    Selected = item.GetPropValue(keyProperty) != null && ids.Contains(item.GetPropValue(keyProperty).ToString().Replace(physicalFilePath, ""))
                }));
            }
            else if (metadata.DataTypeName == "ModelRepeater")
            {
                foreach (var item in htmlHelper.ViewData.Model)
                {
                    var itemObject = (Object)item;

                    items.Add(new SelectListItem()
                    {
                        Text     = GetDisplayString(htmlHelper, item, valueProperty),
                        Value    = itemObject.GetPropValue(keyProperty) != null ? itemObject.GetPropValue(keyProperty).ToString() : "",
                        Selected = itemObject.GetPropValue(keyProperty) != null && ids.Contains(itemObject.GetPropValue(keyProperty).ToString())
                    });
                }
            }
            else
            {
                //db
                if (options == null)
                {
                    using (var db = htmlHelper.DatabaseByEntityType(dropdownModelType))
                    {
                        var pi = dropdownModelType.GetProperty(orderByProperty);

                        Type iQueryableType = typeof(IQueryable <>).MakeGenericType(new[] { dropdownModelType });

                        IQueryable query = db.Queryable(dropdownModelType);

                        if (selectedOnly)
                        {
                            var whereClause = LamdaHelper.SearchForEntityByIds(dropdownModelType, ids.Cast <Object>());
                            query = (IQueryable)typeof(LamdaHelper).GetMethod(nameof(LamdaHelper.Where)).MakeGenericMethod(dropdownModelType).Invoke(null, new object[] { query, whereClause });
                        }
                        else
                        {
                            if (metadata.AdditionalValues.ContainsKey("WhereClauseEqualsDictionary"))
                            {
                                var whereClauseEqualsDictionary = (Dictionary <string, List <object> >)metadata.AdditionalValues["WhereClauseEqualsDictionary"];
                                foreach (var where in whereClauseEqualsDictionary)
                                {
                                    var whereClause = LamdaHelper.SearchForEntityByProperty(dropdownModelType, where.Key, where.Value);
                                    query = (IQueryable)typeof(LamdaHelper).GetMethod(nameof(LamdaHelper.Where)).MakeGenericMethod(dropdownModelType).Invoke(null, new object[] { query, whereClause });
                                }
                            }

                            if (!string.IsNullOrWhiteSpace(orderByProperty))
                            {
                                if (orderByType == "asc")
                                {
                                    query = (IQueryable)typeof(Utilities).GetMethod(nameof(Utilities.QueryableOrderBy)).MakeGenericMethod(dropdownModelType).Invoke(null, new object[] { query, orderByProperty, true });
                                }
                                else
                                {
                                    query = (IQueryable)typeof(Utilities).GetMethod(nameof(Utilities.QueryableOrderBy)).MakeGenericMethod(dropdownModelType).Invoke(null, new object[] { query, orderByProperty, false });
                                }
                            }
                        }

                        IEnumerable results = query.ToList(dropdownModelType);

                        foreach (var item in results)
                        {
                            items.Add(new SelectListItem()
                            {
                                Text = GetDisplayString(htmlHelper, item, valueProperty),
                                //Value = item.GetPropValue(keyProperty) != null ? item.GetPropValue(keyProperty).ToString() : "",
                                //Selected = item.GetPropValue(keyProperty) != null && ids.Contains(item.GetPropValue(keyProperty).ToString())
                                Value    = GetDisplayString(htmlHelper, item, keyProperty),
                                Selected = ids.Contains(GetDisplayString(htmlHelper, item, keyProperty))
                            });
                        }
                    }
                }
                else
                {
                    options.ToList().ForEach(item =>
                                             items.Add(new SelectListItem()
                    {
                        Text     = item,
                        Value    = item,
                        Selected = ids.Contains(item)
                    }));
                }
            }

            if (metadata.IsNullableValueType || nullable)
            {
                items.Insert(0, new SelectListItem {
                    Text = "", Value = ""
                });
            }

            return(items);
        }