使用多个 DbContext 出现错误无法在单个查询执行中使用多个 DbContext 实例

use*_*812 5 c# entity-framework-core asp.net-core-mvc

我使用 .NET Core 3 启动了一个新的 MVC 应用程序。我有三个 DbContext 文件,它们使用三个不同的数据库:用于我的主应用程序的 ComplaintDbContext、用于 Identity 用户的 IdentityCoreDbContext 以及用于我的员工数据库的 EmployeeDbContext。

在我的应用程序中,我有一个名为 ComplaintRepository 的存储库类,其构造函数如下所示:

public ComplaintRepository(ComplaintDbContext context, 
        EmployeeDbContext employeeContext)
    {
        _context = context;
        _employeeContext = employeeContext;
    }
Run Code Online (Sandbox Code Playgroud)

在我的 ComplaintController 中,我需要从两个数据库获取数据。我可以从投诉数据库获取数据,但是一旦我调用从员工数据库获取数据的操作,就会收到错误:

无法在单个查询执行中使用多个 DbContext 实例。确保查询使用单个上下文实例。

我尝试过这样的事情:

public class FrameworkContext : DbContext
{
    public DbSet<Customer> Customers { get; set; }
}

public class ExtendedContext : FrameworkContext
{
    public DbSet<Order> Orders { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我无法让它工作。任何帮助,将不胜感激。谢谢!

编辑:

我启动了一个名为 EmployeeRepository 的新存储库来分离关注点。这是给我带来问题的操作:

    public IEnumerable<ApplicationUser> GetWorkerList()
    {
        var employees = _employeeRepository.GetEmployeesByUnit(22);

        //Get ApplicationUsers where user exists in Employees list
        IEnumerable<ApplicationUser> userList = _userManager.Users
            .Where(emp => employees.Any(e => emp.EmployeeID == e.EmployeeId)).OrderBy(e => e.LastName);

        return userList;            
    }
Run Code Online (Sandbox Code Playgroud)

我的员工数据库和身份数据库共享一个名为 EmployeeId 的列。

当我尝试将其更改为使用 ToList() 时,我开始收到不同的错误:

InvalidOperationException:LINQ 表达式 'Where( 源:DbSet,谓词:(a) => Any( 源:(未处理的参数:__employees_0),谓词:(e) => a.EmployeeID == e.EmployeeId))' 无法被翻译。以可翻译的形式重写查询,或者通过插入对 AsEnumerable()、AsAsyncEnumerable()、ToList() 或 ToListAsync() 的调用来显式切换到客户端计算。

编辑:

我按照周涛的建议使用 ToList() 并且能够让它工作。我在我的存储库中替换了 IEnumerable 以使用它:

    public List<TblEmployee> GetEmployeesByUnit(int unitId)
    {
        var emp = _context.TblEmployee.Where(e => e.UnitId == unitId &&
                e.TermDate == null)
            .OrderBy(e => e.LastName).ToList();

        return emp;
    }
Run Code Online (Sandbox Code Playgroud)

在我的控制器中我基本上做了同样的事情,现在我有这个:

    public List<ApplicationUser> GetWorkerList()
    {
        var employees = _employeeRepository.GetEmployeesByUnit(22);

        List<ApplicationUser> userList = new List<ApplicationUser>();

        //Get ApplicationUsers where user exists in Employees list
        foreach (TblEmployee emp in employees)
        {
            ApplicationUser user = _userManager.Users
                .Where(e => e.EmployeeID == emp.EmployeeId).FirstOrDefault();

            userList.Add(user);
        }

        return userList;            
    }
Run Code Online (Sandbox Code Playgroud)

我想使用 LINQ 而不是 foreach 循环。

Ari*_*awa 0

我也遇到了同样的问题,据我所知,您不能对同一查询使用不同的 DbContext。只需确保您对相同的查询使用相同的 DbContext 对象。