Friday, 4 June 2010

How to perform cross database LINQ join operation

Hello Folks,

Today I will tell you how we can use the power of LINQ to perform join on tables from two different database.
Idea is very much similar to the way we perform join on the tables within a single database with little twist.

After dragging the table from first database, try dragging the table from the second database. Visual studio will give warning but ignore it.
I say Ignore it as it will just change the connection string. This should not be a matter of concern as long as both the database are within the same database engine.
And then go to the property of first table and change the  source value to fully qualified name i.e. <DatabaseName>.dbo.<TableName>

See the steps described below:
































And then right the code to perform join operation.

static void Main(string[] args)
        {
            CrossDBLinqDataContext crossdbContext = new CrossDBLinqDataContext();
            var result = from t1 in crossdbContext.Test1Tables
                         join t2 in crossdbContext.Test2Tables on t1.Id equals t2.id
                         select new { t1, t2 };

            foreach (var item in result)
            {
                Console.WriteLine(item.t1.name);
                Console.WriteLine(item.t2.name);
            }
        } 


Happy Coding :)

9 comments:

  1. Great Post! I've been struggling since morning to do cross database join using LINQ to SQL...You've made my day! Thanks a lot!

    ReplyDelete
  2. Really great post. I was wondering if this was possible. I am going to test it.
    Thanks

    ReplyDelete
  3. Hello Tudor...
    Can you please let me know the steps that you are following...this will help me figure out the issue.

    ReplyDelete
  4. Where can you drag & drop this way? I tried the model without success.

    ReplyDelete
  5. Great tip, Thanks!

    ReplyDelete
  6. i can't buid project.
    please help me.
    thanks

    ReplyDelete
  7. Hi,

    I tried this technique, but I'm getting these errors:

    Error 18 'Public Property FirstName() As String' has multiple definitions with identical signatures

    Ed

    ReplyDelete
  8. How would this work if the databases are named differently on different servers?

    E.g., you have Test1 and Test2 dbs, but what if they were named TestA and TestB on a different server (with the same schema). Normally I handle this with passing a connection string to the context object but it's not clear how to handle it here...

    ReplyDelete