I'm writing a IQueryable<T> extension method and I would like to get the foreign keys of the navigation properties of T. I have figured out that I can get access to them through IModel.FindEntityType(T).GetNavigations(), the question is how to best get access to the IModel while keeping the method as simple as possible.
At the moment the method looks something like this:
public static IQueryable<TQuery> DoMagic<TQuery>(this IQueryable<TQuery> query, IModel model)
{
var entity = model.FindEntityType(entityType);
var navigationProperties = entity.GetNavigations();
...
}
I would love if I wouldn't need to pass IModel as an argument like this:
public static IQueryable<TQuery> DoMagic<TQuery>(this IQueryable<TQuery> query)
{
var entity = Model.FindEntityType(entityType);
var navigationProperties = entity.GetNavigations();
...
}
I have considered adding a IServiceCollection extension method and passing the DbContext and setting IModel as a static property to the IQueryable<T> extension method. The problem with that is that it is limiting me to one DbContext.
I have also looked into the option to add a extension method to DbContextOptionsBuilder but haven't really figured out best way to achieve what I want to do this way.
Maybe there is other ways to get access to the foreign keys? Any help is greatly appreciated!
Edit
From the navigation properties I want to access the ForeignKey-property to know what property is used to resolve the navigation property. Something like:
navigationProperties.ToList().Select(x => x.ForeignKey);