Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is there any way to implement cross database querying in Entity Framework? Let's imagine I've two Entities User and Post, User entity is in database1 and Post is in database2, which means those entities are in separate databases. How should I get user's posts in Entity Framework ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
210 views
Welcome To Ask or Share your Answers For Others

1 Answer

I know this is an old question, but this is actually 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 procedures.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...