首页 > 解决方案 > 如何在 EF Core 3 中动态获取 DbSet?

问题描述

你好我正在尝试这样做:

我有更多的类,用户可以在其中存储文件-这些文件的路径以 JSON 格式存储在 DB 中,文件存储在名为类的文件夹中(因此,当类名为 Foo 时,文件将存储在 Files/Foo/Foobar .pdf)。

我有一个控制器,我在其中发送应该删除的文件的路径。在这里我无法解决问题,我也需要从数据库中删除这个文件路径,但我不知道如何动态获取 DbSet。

我在这里搜索了很多问题,但几乎每次我都找到了 DbContext.Set(),但这种方法在 ASP.NET CORE 3.0 中不存在。你能帮我怎么做吗?

这是我的控制器:

[HttpGet]
        public JsonResult DeleteFile(string id)
        {
            KeyValuePair<string, string> message;
            if (!string.IsNullOrEmpty(id))
            {
                string filePath = Uri.UnescapeDataString(id);
                if (filePath.CheckIfExists())
                {
                    string nameOfInstance = filePath.GetNumberAccordingToFileName();
                    string tableName = filePath[1..(filePath.IndexOf('/', 1) - 1)];
                    Type type = Assembly.GetExecutingAssembly()
                            .GetTypes()
                            .FirstOrDefault(t => t.Name.Equals(tableName,StringComparison.OrdinalIgnoreCase));
                    if(type.IsClass)
                    {
                        var entity = db.GetDbSet(Activator.CreateInstance(type)); //this is not working
                        var item = entity.GetDataFromDbase(nameOfInstance,1,0,"Number","ASC","Number",false,out int filteredResultsCount, out int totalResultsCount, false).FirstOrDefault(); //find the item
                        item = item.DeleteFileFromItem(User.Identity.Name, filePath);
                        db.Update(item);
                        var result = db.SaveChanges(); 
                        if (result > 0)
                        {
                            if (filePath.DeleteFile())
                            {
                                message = new KeyValuePair<string, string>(MessagesHandler.Success, $"File {filePath.Substring(filePath.LastIndexOf("/"))} was successfully deleted.");
                                return Json(new
                                {
                                    status = true,
                                    message
                                });
                            }
                            else
                            {
                                message = new KeyValuePair<string, string>(MessagesHandler.Error, $"File {filePath.Substring(filePath.LastIndexOf("/"))} was not deleted.");
                                return Json(new
                                {
                                    status = false,
                                    message
                                });
                            }
                        } //if the changes were not made in DB
                        message = new KeyValuePair<string, string>(MessagesHandler.Error, $"File {filePath.Substring(filePath.LastIndexOf("/"))} was deleted, error in DB");
                        return Json(new
                        {
                            status = false,
                            message
                        });
                    }

                    
                }//error message when file not found
                message = new KeyValuePair<string, string>(MessagesHandler.Error, $"File {filePath} not found.");
                return Json(new
                {
                    status = false,
                    message
                });
            }//error message when filename is empty
            message = new KeyValuePair<string, string>(MessagesHandler.Error, $"Field ID cannot be empty");
            return Json(new
            {
                status = false,
                message
            });
        }

这是GetDbSet方法:

public static Microsoft.EntityFrameworkCore.DbSet<TEntity> GetDbSet<TEntity>(this DataContext db, TEntity t) where TEntity : class
        {
            Type type = t.GetType();
        return (Microsoft.EntityFrameworkCore.DbSet<TEntity>)typeof(DataContext).GetMethod(nameof(DataContext.Set)).MakeGenericMethod(type).Invoke(db, null);
        }

在这里我得到了这个例外:

System.InvalidCastException HResult=0x80004002 消息=无法转换类型为“Microsoft.EntityFrameworkCore.Internal.InternalDbSet 1[SmartLab_System.Models.TestRequirement]' to type 'Microsoft.EntityFrameworkCore.DbSet1[System.Object]”的对象。

方法 GetDataFromDbase:

public static List<T> GetDataFromDbase<T>(this IEnumerable<T> entity, string searchBy, int take, int skip, string sortBy,
            string sortDir, string columnName, bool showDeactivatedItems, out int filteredResultsCount, out int totalResultsCount, bool countResult = true) where T : class
        {
            IEnumerable<T> helper;
            if (!String.IsNullOrEmpty(searchBy))//if any string to search was given
            {
                //find the properties we would like to search in
                var properties = typeof(T).GetProperties()
                                    .Where(x => x.CanRead && columnName.Contains(x.Name, StringComparison.InvariantCultureIgnoreCase) && columnName.Length == x.Name.Length)
                                    .Select(x => x.GetMethod)
                                    .Where(x => !x.IsStatic);
                                    //.ToList();

                //list of all items where searched value was found
                helper = entity.GetActiveItems(showDeactivatedItems)
                            .Where(m => properties
                                .Select(p => p.Invoke(m, null)?.ToString() ?? string.Empty)
                                .Any(a => a.ToString().Contains(searchBy, StringComparison.InvariantCultureIgnoreCase)) == true);
                            //.ToList();
            }
            else//if no string to search was given
            {
                helper = entity.GetActiveItems(showDeactivatedItems); //all items
            }

            List<T> result;
            if (take < 1)
            {
                result = helper
                            .OrderBy(sortBy + " " + sortDir)
                            .ToList();
            }
            else
            {
                result = helper
                           .OrderBy(sortBy + " " + sortDir)
                           .Skip(skip)
                           .Take(take)
                           .ToList();
            }

            if (countResult)
            {
                filteredResultsCount = helper.Count();//how many items is sent
                totalResultsCount = entity.Count(); //how many items is in database
            }
            else
            {
                filteredResultsCount = 0;//how many items is sent
                totalResultsCount = 0;
            }

        return result;

    }

除了打电话db.GetDbSet(type)我也试过db.GetDbSet(Activator.CreateInstance(type))但没有工作。

标签: c#entity-framework-core-3.0

解决方案


我在评论中发布的链接(EF Core 2.0 中的动态访问表)将为您检索该集合,但您无法对其进行操作,因为它属于 typeIQueryable而不是IQueryable<T>.

我认为可以通过使用简单的开关和实体上的通用接口来为您提供更好的解决方案。只要您的数据库中没有 100 多个表,这将很容易维护。

                var entityType = "Drawer";
                var pathToRemove = "somepath";
                var id = 1;

                // get queryable based on entity type
                IQueryable<IHasFiles> queryable = entityType switch
                {
                    "Drawer" => context.Set<Drawer>().OfType<IHasFiles>(),
                    "Bookshelf" => context.Set<Bookshelf>().OfType<IHasFiles>(),
                    _ => throw new ArgumentException("Unknown entity type", nameof(entityType))
                };

                // pick the item and include all files
                var item = await queryable.Where(i => i.Id == id).Include(i => i.Files).SingleAsync();

                // pick the correct file
                var file = item.Files.Single(f => f.Path == pathToRemove);

                // remove it
                item.Files.Remove(file);

                // save changes to db
                await context.SaveChangesAsync();

随着实体的定义是这样的

        public interface IHasFiles
        {
            int Id { get; }
            ICollection<File> Files { get; set; }
        }

        public class File
        {
            public int Id { get; set; }
            public string Path { get; set; }
        }

        public class Drawer : IHasFiles
        {
            public int Id { get; set; }

            public ICollection<File> Files { get; set; }
        }

        public class Bookshelf : IHasFiles
        {
            public int Id { get; set; }

            public ICollection<File> Files { get; set; }
        }

推荐阅读