简体   繁体   中英

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

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:(

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM