Convert string reference name to a lambda expression query.
This is my tested code:
protected readonly ApplicationDbContext _context;
public AssetRequestController(ApplicationDbContext context)
{
_context = context;
}
string tableName = "FlowStep";
var dbset = QueryExtensions.Query(_context, tableName);
public static partial class QueryExtensions
{
public static IQueryable Query(this DbContext context, string entityName) =>
context.Query(context.Model.FindEntityType(entityName).ClrType);
static readonly MethodInfo SetMethod = typeof(DbContext).GetMethod(nameof(DbContext.Set));
public static IQueryable Query(this DbContext context, Type entityType) =>
(IQueryable)SetMethod.MakeGenericMethod(entityType).Invoke(context, null);
}
My DbContext
public class ApplicationDbContext : IdentityDbContext
{
public DbSet<FlowStep> FlowStep { get; set; }
}
I am using System.Linq.Dynamic.Core to dynamically add in lambda expressions to queries in EF.
I want to convert a string name (model name) to lambda expressions query. I found this answer.
Dynamically access table in EF Core 2.0
But it gives an error
System.NullReferenceException: 'Object reference not set to an instance of >an object.'
Microsoft.EntityFrameworkCore.Metadata.IModel.FindEntityType(...) returned >null.