This has been asked before and answered, but for .Net Framework. I'm struggling to achieve the same functionality in .Net Core.
I have a method which receives Entity name as a string (along with some selection criteria). I want to get the Entity type using the entityName string and query EF.
Previous answer using EF 6 suggested the following
public async Task<bool> MyMethod(string _type)
{
Type type = Type.GetType(_type);
var tableSet = _context.Set(type);
var list = await db.ToListAsync();
// do something
}
// pass the full namespace of class
var result = await MyMethod("Namespace.Models.MyClass")
Unfortunately context.Set
no longer accepts a parameter so this isn't possible.
I've tried several methods to get and use the type with the context, but I'm hitting a brick wall. I'll dump the test code here - but none of this achieves what I want.
public IList LoadByKey(string entityName, params string[] parameters)
{
// Get type from entity name string - Include assembly
Type clType = Type.GetType($"{entityName},Savant.Pulse.Testbeds.ReferenceData.DB");
// Create instance using the type retrieved from GetType, still just an Object
var instantiatedObject = Activator.CreateInstance(clType);
// Get the entity type from the context itself. This does return the correct type.
// So I thought I was heading in the correct direction.
var entityType = _context.Model.FindEntityType(entityName);
// Get a DbSet of the correct type. Once again this does return what you think you'd need.
// But it's an Object? type returned. I can't seem to cast it to the correct type from the entityName.
var dbSet = _context.GetType().GetProperty(entityType.ClrType.Name).GetValue(_context);
throw new System.NotImplementedException();
}