Cross database querying in EF

c# cross-database entity-framework sql-server

Accepted Answer

Cross-database queries are not supported by the EF context. You must use posts from database1 as a component of that database by making them visible through SQL View (instead of).

24
1/15/2013 4:09:50 PM

Popular Answer

Even though this is an old query, it is actually conceivable. You only need to utilize an if the databases are on the same server.DbCommandInterceptor .

For instance, if I add aDbCommandInterceptor to MyContext I have the ability to stop all command executions and switch the query's given table(s) with my full-db paths.

public override void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
{
    // Here, I can just replace the CommandText on the DbCommand - but remember I
    // want to only do it on MyContext
    var context = contexts.FirstOrDefault() as MyContext;
    if (context != null)
    {
        command.CommandText = command.CommandText
            .Replace("[dbo].[ReplaceMe1]", "[Database1].[dbo].[Customers]")
            .Replace("[dbo].[ReplaceMe2]", "[Database2].[dbo].[Addresses]")
            .Replace("[dbo].[ReplaceMe3]", "[Database3].[dbo].[Sales]");
    }

    base.ReaderExecuting(command, interceptionContext);
}

What's wonderful about this method is that the EF Model Mapping still functions correctly, respects column characteristics, doesn't call for any views, and doesn't call for any stored procedures.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow