.net Core EF - Dynamically Add to DbSet by string name or type

.net .net-core c# entity-framework entity-framework-core

Question

Suppose I have a thousand classes that all inherit one base class, and each of these classes (not the base) has a table, each of which has the same required columns. How can I use reflection or generics to add or update a row in the correct table? I'll know the name of the specific entity at runtime.

There are a handful of stackoverflow posts about getting a dbset with reflection, but the answer results in an IQueryable, which you cannot add a new item to. Those posters seem content with that because they're just fetching data I suppose. I need a DbSet so I can add and update. I can get the fully qualified entity name and type, but how do I get a DbSet with that? I don't want to write a 1000 line switch statement :(

1
1
10/2/2019 9:50:26 PM

Accepted Answer

I ended up using magic strings to add all the properties I knew would be present in the base class. Although not ideal, it did add to the correct table which was the ultimate goal.

            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);
0
10/18/2019 2:27:30 PM

Popular Answer

You can do it by dynamically creating a new type that inherits from DbContext and the use Reflection Emit to add the DbSets to this type.

It's a bit of a long solution to try and post into a response here, but here's a GitHub link to a working demo of how it can be done - EF Core Dynamic Db Context



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow