title: Use different Entity Manager in the Repository of specific Entity objects
body: <p>I've followed the <a href="https://symfony.com/doc/current/doctrine/multiple_entity_managers.html" rel="nofollow noreferrer">How to Work with multiple Entity Managers and Connections</a> chapter in the manual to configure and use different entity managers in my app, as some entities are stored in different database servers.</p>
  
  <p>In the controller I need to use the 2 entity managers: the default for clients, numbers and payments, and the other for contracts.</p>
  
  <p>However, when I call the repository custom method <code>fetchMainByClient()</code> for contracts, which should use the "custom" entity manager instead of the default one, I get a database error, which shows that's using the default entity manager in the repository.</p>
  
  <blockquote>
    <p>An exception occurred while executing 'SELECT ...  FROM CONTRACTS c0_
    WHERE c0_.ClientId = ? AND c0_.Type = 'Main'' with params [35736]:</p>
    
    <p>SQLSTATE[42S02]: Base table or view not found: 1146 Table
    'DEFAULTDB.CONTRACTS' doesn't exist</p>
  </blockquote>
  
  <p>The same error occurs if I try to use an already available repository method, like <code>findOneBy()</code>.</p>
  
  <p>What am I doing wrong?</p>
  
  <p>Here's the Controller's, the Repository's code and the Contract entity header, as well as the doctrine configuration. It's not the real one, but it's similar.</p>
  
  <h2>Controller</h2>
  
  <pre><code>public function index(Request $request, PaymentsRepository $payments_repository): Response
  {
      $payments = $payments_repository-&gt;findLatest($page, $this-&gt;getUser()-&gt;getId());
  
      $form = $this-&gt;createForm(CreatePaymentType::class);
  
      $form-&gt;handleRequest($request);
  
      if ($form-&gt;isSubmitted() &amp;&amp; $form-&gt;isValid()) {
          $payment = $form-&gt;getData();
  
          $em = $this-&gt;get('doctrine.orm.default_entity_manager');
          $cr = $em-&gt;getRepository(Numbers::class);
          $number = $tr-&gt;findOneByNumber($payment-&gt;getNumber());
  
          if (!$number) {
              $this-&gt;addFlash('error', 'numbers.missing_number');
          } else {
              $client = $number-&gt;getClients();
              if (!$client) {
                  $this-&gt;addFlash('error', 'clients.missing_client');
              } else {
                  //$em_custom = $this-&gt;get('doctrine.orm.custom_entity_manager');
                  $em_custom = $this-&gt;getDoctrine()-&gt;getManager('custom');
                  $contracts_repo = $em_custom-&gt;getRepository(Contracts::class);
                  //dump($em, $em_custom, $contracts_repo);
  
                  $contract = $contracts_repo-&gt;fetchMainByClient($client-&gt;getId());
                  $contracts_repo-&gt;increaseCredit($payment-&gt;getValue());
  
                  $payment-&gt;setDate(...);
                  $payment-&gt;setClientId($client-&gt;getId());
                  ...
                  $em-&gt;persist($payment);
                  $em-&gt;flush();
  
                  $this-&gt;addFlash('success', 'flash.success_insert');
  
                  return $this-&gt;redirectToRoute('payments_paginated', ['page' =&gt; $page]);
              }
          }
      }
  
      return $this-&gt;render('carregamentos/index.html.twig', [
          'payments' =&gt; $payments,
          'form' =&gt; $form-&gt;createView(),
      ]);
  }
  </code></pre>
  
  <h2>Repository</h2>
  
  <pre><code>namespace App\Repository;
  
  use App\Entity\Custom\Contratos;
  
  ...
  use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
  use Doctrine\Common\Persistence\ManagerRegistry;
  
  class ContractsRepository extends ServiceEntityRepository
  
      public function __construct(ManagerRegistry $registry)
      {
          parent::__construct($registry, Contracts::class);
      }
  
      /**
       * @return Contracts Returns the Contracts object for the ClientId
       */
      public function fetchMainByClient($value): ?Contracts
      {
          return $this-&gt;createQueryBuilder('c')
              -&gt;andWhere('c.clientid = :val')
              -&gt;andWhere('c.type = \'Main\'')
              -&gt;setParameter('val', $value)
              -&gt;getQuery()
              -&gt;getOneOrNullResult()
          ;
      }
  }
  </code></pre>
  
  <h2>Doctrine configuration</h2>
  
  <pre><code>doctrine:
      dbal:
          default_connection: default
          connections:
              default:
                  driver: 'pdo_mysql'
                  server_version: '5.6'
                  charset: utf8
                  default_table_options:
                      charset: utf8
                      collate: utf8_unicode_ci
  
                  url: '%env(resolve:DATABASE_URL)%'
  
              custom:
                  driver: 'pdo_mysql'
                  server_version: '5.6'
                  charset: utf8
                  default_table_options:
                      charset: utf8
                      collate: utf8_unicode_ci
  
                  url: '%env(resolve:DATABASE_CUSTOM_URL)%'
                  mapping_types:
                      enum: string
                      set:  string
  
      orm:
          auto_generate_proxy_classes: '%kernel.debug%'
          default_entity_manager: default
          entity_managers:
              default:
                  connection: default
                  naming_strategy: doctrine.orm.naming_strategy.underscore
                  mappings:
                      Main:
                          is_bundle: false
                          type: annotation
                          dir: '%kernel.project_dir%/src/Entity'
                          prefix: 'App\Entity'
                          alias: Main
              custom:
                  connection: custom
                  naming_strategy: doctrine.orm.naming_strategy.underscore
                  mappings:
                      Custom:
                          is_bundle: false
                          type: annotation
                          dir: '%kernel.project_dir%/src/Entity/Custom'
                          prefix: 'App\Entity\Custom'
                          alias: Custom
  </code></pre>
  
  <h2>Entity header with ORM mapping</h2>
  
  <pre><code>namespace App\Entity\Custom;
  
  use Doctrine\ORM\Mapping as ORM;
  
  /**
   * Contracts.
   *
   * @ORM\Table(name="CONTRACTS", indexes={@ORM\Index(name="clientid", columns={"clientid"})})
   * @ORM\Entity(repositoryClass="App\Repository\ContractsRepository")
   */
  class Contracts
  {
      ...
  }
  </code></pre>