Search code examples
c#sql-serverormentity-framework-coreasp.net-core-2.2

Use multiple huge databases in one Entity Framework Core query with SQL Server?


I want to query multiple tables from different databases in one single query with 1 or 2 dbcontext. I've been searching for some info, and it seems not easy to make it work perfectly.

I need to make several queries with 5 or 6 tables from 3 or 4 different databases at the same time.

  • I've tried using the implementation of a dbcontext into the another but I'm having a problem with the primary keys which I don't have if I only use one database.
  • I've tried 2 dbcontext separately, but I'm getting an error:

Cannot use multiple DbContext instances within a single query execution message.

I've read that I can relate the 2 databases, the thing is I cannot do that because of the structure of my enterprise, and it doesn't allow me to.

This is in Entity Framework Core 2.2 or 3, I already tried both. I have already the databases created, so I scaffolded them.

I have a single example, with only 2 databases:

var data =
   from j in jsa.TbEmp
   join i in info.TbcEmpGral on j.fiEmp equals i.fiEmp
   where i.fiEmp == 361591
   select i.FcName.ToString() + " - " + i.fiDate.ToString();

Solution

  • I want to query multiple tables from different databases [on one server] in one single query

    The simplest way to do this is to create views or synonyms for all the tables in a single database. EF won't be able to scaffold the model automatically, but if you create the model by-hand EF will simply send SQL to that single database as if it contained all the tables, and SQL Server will redirect the queries to the appropriate objects through the synonyms or views.