Cannot use multiple context instances within a single query execution. Ensure the query uses a single context instance

Dharmesh Sharma 1 Reputation point
2022-01-03T16:52:29.6+00:00

I am getting error for multiple dbcontext like

Cannot use multiple context instances within a single query execution. Ensure the query uses a single context instance.'

But I am using repository pattern with Autofac with one database when trying to join its showing like i am using two dbcontext.
code is

private readonly IRepository<AdminFlightInventoryMaster> _adminFlightIventoryMasterRepository;
 private readonly IRepository<AdminFlightInventoryDetails> _adminInventoryDetailsRepository;
 public AdminFlightInventoryMasterService(IRepository<AdminFlightInventoryMaster> adminFlightIventoryMasterRepository, IRepository<AdminFlightInventoryDetails> adminInventoryDetailsRepository)
        {
            _adminFlightIventoryMasterRepository = adminFlightIventoryMasterRepository;
            _adminInventoryDetailsRepository = adminInventoryDetailsRepository;
        }

public virtual IPagedList<AdminFlightInventoryMaster> SearchInventory(string source, string destination, DateTime travelDate)
        {
            var query = _adminFlightIventoryMasterRepository.Table;
            query = query.Where(x => x.SourceCode == source && x.DestinationCode == destination && x.IsDeleted == false && x.IsActive == true);
            query = from x in query
                    join
                     d in _adminInventoryDetailsRepository.Table
                     on x.ID equals d.AdminInventoryMasterId
                    where d.StartDate.Date == travelDate.Date
                    select x;
            query = query.OrderBy(x => x.ID);
            var result = new PagedList<AdminFlightInventoryMaster>(query, 0, 100);
            return result;

        }

when I return then getting error

System.InvalidOperationException: 'Cannot use multiple context instances within a single query execution. Ensure the query uses a single context instance.'

Register the dependency

//data layer
builder.Register(context => new GutObjectContext(context.Resolve<DbContextOptions<GutObjectContext>>()))
                .As<IDbContext>().InstancePerLifetimeScope();
//repositories
        builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>)).InstancePerLifetimeScope();

why I am getting this error

These all code working in .net core 2.1

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
741 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,559 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.