2

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?

IvanH
  • 5,039
  • 14
  • 60
  • 81
  • Why exactly do you want that? – Guru Stron Jul 26 '23 at 09:05
  • 1
    *I don't see a direct way to get the name of the DbSet property from the navigation property expression* - because EF do not use `DbContext` properties for query building and do not store such information. They exist only for сonvenience of developer. IOW it is possible to have `DbContext` without these properties, but still working. – Svyatoslav Danyliv Jul 26 '23 at 09:08
  • @GuruStron I have two intentions in mind. First diagnostics logging of queries including navigation properties by parameters. The second one is for caching - from DbSet properties I derive tables and I can track changes in DB whether the chache is still valid. – IvanH Jul 26 '23 at 09:17
  • _"The second one is for caching - from DbSet properties I derive tables and I can track changes in DB whether the chache is still valid."_ - I would argue that it would be better to use change tracker for such things. As for logging it is hard to tell. – Guru Stron Jul 26 '23 at 09:24

0 Answers0