<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:a10="http://www.w3.org/2005/Atom" version="2.0">
  <channel xmlns:media="http://search.yahoo.com/mrss/" xmlns:content="http://purl.org/rss/1.0/modules/content/">
    <title>ABP.IO Stories</title>
    <link>https://abp.io/community/articles</link>
    <description>A hub for ABP Framework, .NET, and software development. Access articles, tutorials, news, and contribute to the ABP community.</description>
    <lastBuildDate>Fri, 02 Oct 2026 16:39:44 Z</lastBuildDate>
    <generator>Community - ABP.IO</generator>
    <image>
      <url>https://abp.io/assets/favicon.ico/favicon-32x32.png</url>
      <title>ABP.IO Stories</title>
      <link>https://abp.io/community/articles</link>
    </image>
    <a10:link rel="self" type="application/rss+xml" title="self" href="https://abp.io/community/rss?member=Ahmad-Nidal" />
    <item>
      <guid isPermaLink="true">https://abp.io/community/posts/how-to-use-multiple-dbcontexts-in-a-single-query-execution-488bxj4q</guid>
      <link>https://abp.io/community/posts/how-to-use-multiple-dbcontexts-in-a-single-query-execution-488bxj4q</link>
      <a10:author>
        <a10:name>Ahmad-Nidal</a10:name>
        <a10:uri>https://abp.io/community/members/Ahmad-Nidal</a10:uri>
      </a10:author>
      <category>entity-framework-core</category>
      <title>How to Use Multiple DbContexts in a Single Query Execution</title>
      <description>In this article, we will explore a solution to query from multiple DbContext instances within a single execution in the ABP Framework with EF Core. </description>
      <pubDate>Wed, 22 May 2024 18:15:28 Z</pubDate>
      <a10:updated>2026-10-02T05:49:13Z</a10:updated>
      <content:encoded><![CDATA[<h1>How to Use Multiple DbContexts in a Single Query Execution</h1>
<h2>Introduction</h2>
<p>It's common to have multiple DbContexts in a single application, especially when your application is modular. However, querying from different repositories, each associated with a different DbContext, can lead to this error:</p>
<pre><code class="language-csharp">System.InvalidOperationException: 'Cannot use multiple context instances within a single query execution. Ensure the query uses a single context instance.'
</code></pre>
<p>This error occurs because EF Core does not support querying from multiple DbContexts in a single query execution.</p>
<p>In this article, we will explore a solution to query from multiple DbContext instances within a single execution in the ABP Framework with EF Core. Specifically, we will focus on a scenario where we have two DbContext instances: one for an ExamsModule and another for the main application (LMSApp). Notably, both DbContext instances in our example connect to the same database.</p>
<p>Additionally, it’s important to note that this workaround is not the only solution. Another approach involves replacing the DbContext and injecting it directly where needed in the host application. This approach is detailed in the <a href="https://docs.abp.io/en/abp/latest/Entity-Framework-Core-Migrations#entityframeworkcore-project">ABP Framework documentation</a>.</p>
<h2>Real-World Example</h2>
<p>Let's say we have two DbContexts: one for the <code>ExamsModule</code> and another for the host application <code>LMSApp</code>. We want to get the <code>Course</code> from the LMSApp DbContext and <code>Exam</code> details from the ExamsModule DbContext in a single query execution.</p>
<h3>LMS Application</h3>
<pre><code class="language-csharp">public class Course&lt;Guid&gt;
{
    public string Title { get; set; }
    public string Description { get; set; }
}

public interface ILMSDbContext : IEfCoreDbContext
{
    DbSet&lt;Course&gt; Courses { get; set; }
}

public class LMSDbContext : AbpDbContext&lt;LMSDbContext&gt;, ILMSDbContext
{
    public DbSet&lt;Course&gt; Courses { get; set; }
}

public interface ICourseRepository : IRepository&lt;Course, Guid&gt;
{
    // Add custom methods here
}

public class CourseRepository : EfCoreRepository&lt;LMSDbContext, Course, Guid&gt;, ICourseRepository
{
    public CourseRepository(IDbContextProvider&lt;LMSDbContext&gt; dbContextProvider) : base(dbContextProvider)
    {
    }

    // Implement custom methods here
}
</code></pre>
<h3>Exams Module</h3>
<pre><code class="language-csharp">public class Exam&lt;Guid&gt;
{
    public string Title { get; set; }
    public DateTime Date { get; set; }
}

public interface IExamDbContext : IEfCoreDbContext
{
    DbSet&lt;Exam&gt; Exams { get; set; }
}

public class ExamDbContext : AbpDbContext&lt;ExamDbContext&gt;, IExamDbContext
{
    public DbSet&lt;Exam&gt; Exams { get; set; }
}

public interface IExamRepository : IRepository&lt;Exam, Guid&gt;
{
    // Add custom methods here
}

public class ExamRepository : EfCoreRepository&lt;ExamDbContext, Exam, Guid&gt;, IExamRepository
{
    public ExamRepository(IDbContextProvider&lt;ExamDbContext&gt; dbContextProvider) : base(dbContextProvider)
    {
    }

    // Implement custom methods here
}
</code></pre>
<h3>Querying from Multiple DbContexts in an Application Service in the Host Application</h3>
<pre><code class="language-csharp">public class CourseExamAppService : ApplicationService
{
    private readonly ICourseRepository _courseRepository;
    private readonly IExamRepository _examRepository;

    public CourseExamAppService(ICourseRepository courseRepository, IExamRepository examRepository)
    {
        _courseRepository = courseRepository;
        _examRepository = examRepository;
    }

    public async Task&lt;CourseExamDto&gt; GetCourseExamAsync(Guid courseId, Guid examId)
    {
        var course = await _courseRepository.GetAsync(courseId);
        var exam = await _examRepository.GetAsync(examId);

        return new CourseExamDto
        {
            CourseTitle = course.Title,
            CourseDescription = course.Description,
            ExamTitle = exam.Title,
            ExamDate = exam.Date
        };
    }
}
</code></pre>
<p>In the above code, we are querying from two different repositories, each in a different DbContext. This will throw the error mentioned earlier.</p>
<h2>Solution</h2>
<p>To solve this issue, we need to abstract the exams repository and implement it using the LMSApp DbContext. This ensures that the two repositories we use will be in the same DbContext (LMSApp DbContext).</p>
<h3>Updated Exam Repository</h3>
<pre><code class="language-csharp">// Abstract Exam Repository to use in the host application
public class AbstractExamRepository&lt;TDbContext&gt; : EfCoreRepository&lt;TDbContext, Exam, Guid&gt;, IExamRepository
    where TDbContext : IExamDbContext
{
    public AbstractExamRepository(IDbContextProvider&lt;TDbContext&gt; dbContextProvider) : base(dbContextProvider)
    {
    }

    // Implement custom methods here
}

// Concrete Exam Repository to use in the ExamsModule
public class ExamRepository : AbstractExamRepository&lt;ExamDbContext&gt;
{
    public ExamRepository(IDbContextProvider&lt;ExamDbContext&gt; dbContextProvider) : base(dbContextProvider)
    {
    }
}
</code></pre>
<h3>AppDbContext</h3>
<pre><code class="language-csharp">public class LMSDbContext : AbpDbContext&lt;LMSDbContext&gt;, ILMSDbContext, IExamDbContext
{
    public DbSet&lt;Course&gt; Courses { get; set; }
    public DbSet&lt;Exam&gt; Exams { get; set; }
}

public interface ILMSExamRepository : IExamRepository
{
}

public class LMSExamRepository : AbstractExamRepository&lt;LMSDbContext&gt;, ILMSExamRepository
{
    public LMSExamRepository(IDbContextProvider&lt;LMSDbContext&gt; dbContextProvider) : base(dbContextProvider)
    {
    }
}
</code></pre>
<p>Then you need to add the new repository to the dependency injection container in the host application.</p>
<pre><code class="language-csharp">public override void ConfigureServices(ServiceConfigurationContext context)
{
    // context.Services.AddScoped&lt;ILMSExamRepository, LMSExamRepository&gt;();
    context.Services.AddAbpDbContext&lt;LMSDbContext&gt;(options =&gt;
    {
        options.AddDefaultRepositories(includeAllEntities: true);
        options.AddRepository&lt;Exam, LMSExamRepository&gt;();
    });
}
</code></pre>
<p>Now, you can use the <code>ILMSExamRepository</code> in the <code>CourseExamAppService</code> to query from both repositories in a single query execution.</p>
<pre><code class="language-csharp">public class CourseExamAppService : ApplicationService
{
    private readonly ICourseRepository _courseRepository;
    private readonly ILMSExamRepository _examRepository;

    public CourseExamAppService(ICourseRepository courseRepository, ILMSExamRepository examRepository)
    {
        _courseRepository = courseRepository;
        _examRepository = examRepository;
    }

    public async Task&lt;CourseExamDto&gt; GetCourseExamAsync(Guid courseId, Guid examId)
    {
        var course = await _courseRepository.GetAsync(courseId);
        var exam = await _examRepository.GetAsync(examId);

        return new CourseExamDto
        {
            CourseTitle = course.Title,
            CourseDescription = course.Description,
            ExamTitle = exam.Title,
            ExamDate = exam.Date
        };
    }
}
</code></pre>
<h2>Conclusion</h2>
<p>In this article, we saw how to query from multiple DbContexts in a single query execution in the ABP Framework. We abstracted the repository and implemented it using the host application DbContext, allowing us to query from multiple repositories in a single query execution.</p>
<p>This article was written by <a href="https://community.abp.io/members/Ahmad-Nidal">Ahmad Nidal</a> with team instructions, especially from <a href="https://community.abp.io/members/qais.alkhateeb@devnas-jo.com">Qais Al-Khateeb</a> and <a href="https://community.abp.io/members/suhaibmousa032@gmail.com">Suhaib Musa</a>.</p>
]]></content:encoded>
      <media:thumbnail url="https://abp.io/images/others/blank-cover-image-150_79.png" />
      <media:content url="https://abp.io/images/others/blank-cover-image-150_79.png" medium="image" />
    </item>
  </channel>
</rss>