0

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();
}
DavidG
  • 113,891
  • 12
  • 217
  • 223
MartinS
  • 6,134
  • 10
  • 34
  • 40
  • Is there a reason you need to use the type as a parameter and not use the generic variant of `context.Set`? – DavidG Feb 24 '20 at 16:14
  • From what I can see: `Type.GetType("Namespace.Models.MyClass")` and then use that with the generic repository methods that are fairly easily documented... Or am I missing something? – Austin T French Feb 24 '20 at 17:04
  • Actually what you trying to achieve already exists - Structured Query Language (SQL) ;) – Fabio Feb 24 '20 at 17:52
  • @Fabio I was thinking exactly that, maybe even switch this reference data service to Dapper. – MartinS Feb 24 '20 at 17:55
  • Here is how you can obtain non generic `IQueryable` - https://stackoverflow.com/questions/48041821/dynamically-access-table-in-ef-core-2-0/48042166#48042166. The problem is that there is not much you can do with it, since all LINQ extension methods are for generic `IQueryable`. Hence you would need some 3rd party extensions like [Dynamic LINQ](https://github.com/StefH/System.Linq.Dynamic.Core#systemlinqdynamiccore) – Ivan Stoev Feb 24 '20 at 17:56

0 Answers0