.net Core EF - 按字符串名称或类型动态添加到 DbSet

Ale*_*lex 5 .net c# entity-framework entity-framework-core .net-core

假设我有一千个类都继承了一个基类,并且这些类中的每一个(不是基类)都有一个表,每个表都有相同的必需列。如何使用反射或泛型在正确的表中添加或更新行?我会在运行时知道特定实体的名称。

有一些关于使用反射获取 dbset 的 stackoverflow 帖子,但答案会导致 IQueryable,您无法向其中添加新项目。那些海报似乎对此很满意,因为我想他们只是在获取数据。我需要一个 DbSet 以便我可以添加和更新。我可以获得完全限定的实体名称和类型,但是如何获得 DbSet 呢?我不想写一个 1000 行的 switch 语句:(

Ale*_*lex 3

我最终使用魔术字符串添加我知道基类中存在的所有属性。虽然不理想,但它确实添加到了正确的表中,这是最终的目标。

            var entityType = Assembly.GetAssembly(typeof(BaseTypeEntity)).GetType(namespacePrefix + typeName);

            // create an instance of that type
            object instance = Activator.CreateInstance(entityType);

            // Get a property on the type that is stored in the 
            // property string
            PropertyInfo prop = entityType.GetProperty("Active");
            prop.SetValue(instance, true, null);
            // .... more properties

            _context.Add(instance);
Run Code Online (Sandbox Code Playgroud)