Cross database querying in EF

我的梦境 提交于 2019-11-27 19:30:01

EF context does not support cross database queries. You need to expose posts in database1 through SQL View (or synonym) and use it as part of that database.

I know this is an old thread, but, actually. this is possible. If the databases are on the same server, then all you need to do is use a DbCommandInterceptor.

As an example, if I attach a DbCommandInterceptor to MyContext, I can intercept all command executions and replace the specified Table(s) in the query 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);
    }

The nice thing also about this approach is that the EF Model Mapping still works properly and respects Column attributes, requires no views, and requires no stored procs.

You can use ExecuteStoreQuery, like:

var myOb = context.ExecuteStoreQuery<PlainOldClrObject>(
        @"select  * 
          from    db1.dbo.table1 t1
          join    db2.dbo.table2 t2
          on      t2.t1_id = t1.id
          where   t1.id  = {0}",
        table1Id).FirstOrDefault();

You'd have to define a PlainOldClrObject class with the columns as properties with getters/setters, like:

class PlainOldClrObject
{
    public int Id ( get; set; }
    public int Name ( get; set; }
    ...
}
zmbq

No, you can't. You will have to create to contexts and do the joining your self. See here.

You could resolve to database trickery, creating a view in one database the reflects a table in the other one.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!