2

After upgrading from .Net Core 2.2 to 3.0, the apps is throwing this err message.

Cannot use multiple DbContext instances within a single query execution

What is the workaround?

IQueryable<ApplicationUser> query;

var queryJoin = from ci in _courseInstructorRepository.Table
        join uc in _userCourseRepository.Table on ci.CourseId equals uc.CourseId
        select new { ci, uc };

if (userId > 0)
    queryJoin = queryJoin.Where(x => x.ci.UserId == userId);

if (courseId > 0)
    queryJoin = queryJoin.Where(x => x.uc.CourseId == courseId);

if (classId > 0)
    queryJoin = queryJoin.Where(x => x.uc.CourseClassId == classId);

query = queryJoin.Select(x => x.uc.User).Distinct();

if (!string.IsNullOrEmpty(studentFirstChar))
    query = query.Where(x => x.FirstName.StartsWith(studentFirstChar));

if (schoolId > 0)
    query = query.Where(x => x.SchoolId == schoolId);

query = query.OrderBy(x => x.UserName);

return new PagedList<ApplicationUser>(query, pageIndex, pageSize);
0

2 Answers 2

2

You have a couple of design flaws in your code that EF core 2 swept under the carpet.

  1. Your repositories don't share one context instance. EF core 2 couldn't create one SQL query from your code either, but it silently switched to client-side evaluation. That is, it just executed two SQL queries and joined them in memory. This must have been highly inefficient. One of the best design decisions in EF core 3 was to abandon automatic client-side evaluation, so now you're getting this error.

  2. You don't use navigation properties. Using an ORM like EF, using manual joins should hardly ever be necessary. The Instructor class should have a navigation property like Courses, and Course a navigation property like Instructor.

  3. Don't use this redundant repository layer anyway. As you're already experiencing in this small piece of code, it usually makes things harder than necessary without any added value.

Sign up to request clarification or add additional context in comments.

1 Comment

Downvoter, care to explain? Maybe you thought I advocated a singleton context instance? It's about one context instance in one unit of work in which various repositories participate.
1

One of your variables was created using another instance of DBContext, so when you try to use it as part of another DBContext's query it throws. The work around is to close the first DBContext and invoke DBContext.Attach(model) on the second.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.