I have the following DbSet
properties defined in my DbContext
class:
public virtual DbSet<Employee> Employees { get; set; }
public virtual DbSet<Company> Companies { get; set; }
public virtual DbSet<Product> Products { get; set; }
Each employee belongs to a company, and each company has some products. I can write the following queries using Entity Framework:
IQueryable<Employee> query1 = context.Employees.Where(e => e.Id == 1);
IQueryable<Employee> query2 = context.Employees.Where(e => e.Id == 1).Include(x => x.Company);
IQueryable<Employee> query3 = context.Employees.Where(e => e.Id == 1).Include(x => x.Company).ThenInclude(x => x.Products);
Given a query, I want to get a list of the names of the DbSet
properties that are included in it. For example, for query2
, I want to get "Employees" and "Companies" as the output.
I tried to inspect the Expression
property of the query, and cast it to a MethodCallExpression
. Then I looked at the Arguments property, which contains a navigation property expression. However, I don't see a direct way to get the name of the DbSet property from the navigation property expression, except by inferring it from the type of the navigation property (e.g., Company => Companies).
Is there a more reliable way to get the names of the DbSet properties included in an Entity Framework query?