1从IQueryable参数获取DbContext

1从IQueryable参数获取DbContext

本文介绍了.Net EF Core 2.1从IQueryable参数获取DbContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个IQueryable扩展方法:

I have an IQueryable extension method:

public static void SomeExt<T>(this IQueryable<T> query, DbContext context) {...}

,我想知道是否有某种方法可以从查询中获取DbContext,以便可以删除DbContext参数,而只留下:

and I would like to know if there is some way to get DbContext from query so that DbContext argument could be removed leaving only:

public static void SomeExt<T>(this IQueryable<T> query) {...}

我已经尝试过这样的事情访问IQueryable后面的DataContext 但它不起作用,得到零字段.

I have tried something like thisAccess DataContext behind IQueryablebut its not working, getting zero fields.

还有一种方法可以从DbSet中获取它
可以从DbSet获取DbContext吗?
myDbSet.GetService<'ICurrentDbContext>().Context;
但这不是我所需要的.我想从查询中获取它吗?

Also there is way to get it from DbSet
Can you get the DbContext from a DbSet?
myDbSet.GetService<'ICurrentDbContext>().Context;
but that's not what I need. I want to get it from Query?

这是查询:
var q = context.Items.Where(a => a.StatusId = 1);

This is the query:
var q = context.Items.Where(a => a.StatusId = 1);

q.SomeExt(context);
vs
q.SomeExt();

q.SomeExt(context);
vs
q.SomeExt();

推荐答案

我已经找到了一种方法

public static DbContext GetDbContext(IQueryable query)
{
    var bindingFlags = BindingFlags.NonPublic | BindingFlags.Instance;
    var queryCompiler = typeof(EntityQueryProvider).GetField("_queryCompiler", bindingFlags).GetValue(query.Provider);
    var queryContextFactory = queryCompiler.GetType().GetField("_queryContextFactory", bindingFlags).GetValue(queryCompiler);

    var dependencies = typeof(RelationalQueryContextFactory).GetProperty("Dependencies", bindingFlags).GetValue(queryContextFactory);
    var queryContextDependencies = typeof(DbContext).Assembly.GetType(typeof(QueryContextDependencies).FullName);
    var stateManagerProperty = queryContextDependencies.GetProperty("StateManager", bindingFlags | BindingFlags.Public).GetValue(dependencies);
    var stateManager = (IStateManager)stateManagerProperty;

    return stateManager.Context;
}

对于EFCore 3代替

For EFCore 3 instead of

.GetProperty("Dependencies", bindingFlags)

使用

.GetField("_dependencies", bindingFlags)

这篇关于.Net EF Core 2.1从IQueryable参数获取DbContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 03:17